这更像是一个“战壕经验”问题。
给定这段javascript
/**
* @param [foo]
* {Object} an optional object (it can be null, undefined, empty, etc..)
* @param [foo.bars]
* {Array} an Array that *might* be in the object
*/
function (foo) {
// I want to get the array, or an empty array in any
// of the odd cases (foo is null, undefined, or foo.bars is not defined)
var bars = [];
if (foo && foo.bars) {
bars = foo.bars
}
// ....
}
我正在尝试缩短它;根据 MDN应该可以写:
function (foo) {
var bars = (foo && foo.bars) || [];
// ...
}
我是否遗漏了一个不起作用的案例(值集或其他浏览器)?有没有更短/更清洁的方法来做到这一点?
在一个更主观的节点上,你会认为不可读吗?
谢谢
最佳答案
这是一种完全有效的方法,只要您知道 foo.bars
从未被定义为非数组的真值(例如 foo = {bars : 1})
。
它并非不可读,因为大多数 Javascript 开发人员都熟悉 &&
和 ||
的工作方式,并一直使用它们来分配默认值。
关于javascript - 使用默认值的逻辑测试结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17701774/