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

标签 javascript

这更像是一个“战壕经验”问题。

给定这段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/

相关文章:

javascript - Instagram 主题标签搜索

javascript - 将对象值替换为外部数组中的值

javascript - 当可拖动开始时更改拖动的对象

javascript - 有没有办法制作包含其他标签的自定义 HTML 标签?

javascript - 如何使用 Node 路径将 Windows 路径转换为 ​​posix 路径

简单 slider 的 Javascript 函数不执行 onclick

javascript - 使用 JQuery 删除空的 tbody

javascript - 如何使用 php/laravel 使用 get 和 post 语句而不重新加载页面

javascript - 为什么我的 jQuery 事件在循环中时绑定(bind)不正确?

javascript - gmap3 在信息窗口中显示地址