Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
436 views
in Technique[技术] by (71.8m points)

javascript - Null Conditional Operators

C# 6.0 has just been released and has a new nice little feature that I'd really like to use in JavaScript. They're called Null-conditional operators. These use a ?. or ?[] syntax.

What these do is essentially allow you to check that the object you've got isn't null, before trying to access a property. If the object is null, then you'll get null as the result of your property access instead.

int? length = customers?.Length;

So here int can be null, and will take that value if customers is null. What is even better is that you can chain these:

int? length = customers?.orders?.Length;

I don't believe we can do this in JavaScript, but I'm wondering what's the neatest way of doing something similar. Generally I find chaining if blocks difficult to read:

var length = null;
if(customers && customers.orders) {
    length = customers.orders.length;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Called "optional chaining", it's currently a TC39 proposal in Stage 4. A Babel plugin however is already available in v7.

Example usage:

const obj = {
  foo: {
    bar: {
      baz: 42,
    },
  },
};

const baz = obj?.foo?.bar?.baz; // 42

const safe = obj?.qux?.baz; // undefined

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...