使用默认值的逻辑测试结果

Using result of logical tests for default values

本文关键字:测试结果 默认值      更新时间:2023-09-26

这更多的是一个"战壕经验"问题。

给定这段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开发都熟悉&&||的工作方式,并一直使用它们来分配默认值。

我一点都不喜欢它。对于传统的程序员来说,如果(foo&&foo.bars)的计算结果为true,那么它的读取结果就好像是true一样,否则它将是一个空数组。

我更希望看到以下内容:

var bars = (foo && foo.bars) ? foo.bars : [];