C#6.0刚刚发布,并且有一个新的不错的小功能,我真的很想在JavaScript中使用它.他们被称为Null条件运算符.这些使用?.
或?[]
语法.
这些操作基本上允许您null
在尝试访问属性之前检查您获得的对象.如果对象是null
,那么您将获得null
属性访问的结果.
int? length = customers?.Length;
Run Code Online (Sandbox Code Playgroud)
所以这里int
可以为null,并且如果customers
为null 则将采用该值.更好的是你可以链接这些:
int? length = customers?.orders?.Length;
Run Code Online (Sandbox Code Playgroud)
我不相信我们可以用JavaScript做到这一点,但我想知道做类似事情的最好方法是什么.通常我发现链接if
块难以阅读:
var length = null;
if(customers && customers.orders) {
length = customers.orders.length;
}
Run Code Online (Sandbox Code Playgroud)
小智 32
被称为"可选链接",它目前是第一阶段的TC39提案.一通天插件不过是在第7版已经上市.
用法示例:
const obj = {
foo: {
bar: {
baz: 42,
},
},
};
const baz = obj?.foo?.bar?.baz; // 42
const safe = obj?.qux?.baz; // undefined
Run Code Online (Sandbox Code Playgroud)
Vla*_*lav 16
JS逻辑运算符返回没有true
或false
,但truly
还是falsy
价值本身.例如在表达式中x && y
,如果x
是falsy,那么它将被返回,否则y
将被返回.所以运算符的真值表是正确的.
在您的情况下,您可以使用表达式customers && customers.orders && customers.orders.Length
获取length
值或第falsy
一个.
你也可以做一些魔术((customers || {}).orders || {}).length
(个人而言,我不喜欢这种语法和可能的垃圾收集压力)
甚至使用maybe
monad.
function Option(value) {
this.value = value;
this.hasValue = !!value;
}
Option.prototype.map = function(s) {
return this.hasValue
? new Option(this.value[s])
: this;
}
Option.prototype.valueOrNull = function() {
return this.hasValue ? this.value : null;
}
var length =
new Option(customers)
.map("orders")
.map("length")
.valueOrNull();
Run Code Online (Sandbox Code Playgroud)
它比以前的所有方法都要长,但是在没有任何魔力的情况下清楚地显示出你的意图.
有几种方法可以提高代码可读性(取决于您的需求):
您已经使用了babeljs(v7 或更高版本)并且您使用了“可选链接”babel 插件(完成的提案)(或只是preset-stage-3):
const length = customers?.orders?.Length;
// With default value (otherwise it will be `undefined`):
const length = customers?.orders?.Length || defaultLength;
// File: .babelrc
{ "plugins": ["@babel/plugin-proposal-optional-chaining"] }
Run Code Online (Sandbox Code Playgroud)您已经在使用lodash(v3.7 或更高版本):使用lodash.get
方法:
var length = _.get(customers, 'orders.length');
// With default value (otherwise it will be `undefined`):
var length = _.get(customers, 'orders.length', defaultLength);
Run Code Online (Sandbox Code Playgroud)普通的javascript:
var length = customers && customers.orders && customers.orders.length;
// With default value (otherwise it may be whatever falsy value "customers" or "customers.orders" might have):
var length = (customers
&& customers.orders
&& customers.orders.length) || defaultLength;
Run Code Online (Sandbox Code Playgroud) 归档时间: |
|
查看次数: |
14825 次 |
最近记录: |