foo的三元简写?foo:bar

Ternary shorthand for foo ? foo : bar

本文关键字:foo bar 三元      更新时间:2023-09-26

我意识到我大部分时间都在使用三元运算符,如下所示:

foo ? foo : bar;

这变得很麻烦,因为可变长度变得很长,例如

appModel.settings.notifications ? appModel.settings.notifications : {};

有什么速记法或更优雅的方法吗?也许是ES6还是ES7

你可以这样写:

var foo = foo || {};
appModel.settings.notifications = appModel.settings.notifications || {};

你也可以累积

options = default.options || foo.options || bar.options || { foo:'bar'};

您可以简单地使用非位布尔运算符:

foo || bar;

在检查零值时,我们现在可以使用逻辑零赋值:

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 || {}