空条件运算符 [英] Null Conditional Operators
问题描述
C#6.0刚刚发布,并且有一个新的不错的小功能,我真的很想在JavaScript中使用它。它们被称为空条件运算符一>。它们使用?。
或?[]
语法。
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.
这些操作基本上允许您在尝试访问属性之前检查您获得的对象是否不是 null
。如果对象是 null
,那么您将获得 null
作为您的属性访问的结果。
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;
所以这里 int
可以为null,并且如果 customers
为null,则将采用该值。更好的是你可以链接这些:
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;
我不相信我们可以用JavaScript做到这一点,但我想知道最好的方法是什么做类似的事情。一般来说,如果块难以阅读,我发现链接:
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;
}
推荐答案
被称为可选链接,它目前是第1阶段中的TC39提案。但是 Babel插件是已在v7中提供。
Called "optional chaining", it's currently a TC39 proposal in Stage 1. A Babel plugin however is already available in v7.
示例用法:
const obj = {
foo: {
bar: {
baz: 42,
},
},
};
const baz = obj?.foo?.bar?.baz; // 42
const safe = obj?.qux?.baz; // undefined
这篇关于空条件运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!