foo 的三进制 shorthand ?富:酒吧
Ternary shorthand for foo ? foo : bar
我意识到我大部分时间都在使用三元运算符,如下所示:
foo ? foo : bar;
这变得很麻烦,因为变量长度变得很长,e。 g.
appModel.settings.notifications ? appModel.settings.notifications : {};
是否有任何 shorthand 或更优雅的方法来做到这一点?
也许 ES6
或 ES7
?
你可以这样写:
var foo = foo || {};
appModel.settings.notifications = appModel.settings.notifications || {};
你也可以累积
options = default.options || foo.options || bar.options || { foo:'bar'};
您可以简单地使用非按位布尔运算符:
foo || bar;
在检查空值时,我们现在可以使用 Logical Nullish Assignment:
foo ??= bar
请参阅 了解无效和虚假之间的区别。
//these statements are the same for nullish values (null and undefined):
//falsy check
foo = foo ? foo : bar;
//falsy check
foo = foo || bar;
//nullish check
foo ??= bar;
我们也可以在这里使用 in
,可能对人类更友好,而且永远不会阻塞。
notifications in appModel.settings || {}
我意识到我大部分时间都在使用三元运算符,如下所示:
foo ? foo : bar;
这变得很麻烦,因为变量长度变得很长,e。 g.
appModel.settings.notifications ? appModel.settings.notifications : {};
是否有任何 shorthand 或更优雅的方法来做到这一点?
也许 ES6
或 ES7
?
你可以这样写:
var foo = foo || {};
appModel.settings.notifications = appModel.settings.notifications || {};
你也可以累积
options = default.options || foo.options || bar.options || { foo:'bar'};
您可以简单地使用非按位布尔运算符:
foo || bar;
在检查空值时,我们现在可以使用 Logical Nullish Assignment:
foo ??= bar
请参阅
//these statements are the same for nullish values (null and undefined):
//falsy check
foo = foo ? foo : bar;
//falsy check
foo = foo || bar;
//nullish check
foo ??= bar;
我们也可以在这里使用 in
,可能对人类更友好,而且永远不会阻塞。
notifications in appModel.settings || {}