JavaScript:检查列表中的元素

标签 javascript arrays list function

我目前正在使用 Marijn Haverbekes 的优秀著作《Eloquent JavaScript》学习 JavaScript。现在有一个练习,您必须编写一个递归函数来返回嵌套列表的第 n 个元素。如果没有这样的元素,该函数应该返回undefined。解决方案如下所示:

function nth(list, n) {
  if (!list)
    return undefined;
  else if (n == 0)
    return list.value;
  else
    return nth(list.rest, n - 1);
}

到目前为止,一切对我来说似乎都很清楚。但是,我真的不明白 if (!list) {} 到底做了什么。这种情况具体如何评估?如果 list 有一个元素 n,为什么它是真的?

完整的练习可以在这里找到: http://eloquentjavascript.net/04_data.html#p_7AnSuS26HF

最佳答案

这个

if (!list)

是一种简写方式

if (list === false || list === 0 || list === '' || list === null || list === undefined || list !== list /* NaN */) ...
<小时/>

!list 将在列表短于 n 个元素时发生。

// 4 is larger than the list length here, (2)
// !list will happen
nth({value: 'a', rest: {value: 'b', rest: null}}, 4)
//=> undefined

// 1 is not larger than the list length
// !list will not happen
// instead, n === 0 happens after recursing 1 time
nth({value: 'a', rest: {value: 'b', rest: null}}, 1)
//=> 'b'

关于JavaScript:检查列表中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38240821/

相关文章:

list - 对象以 "s"结尾时的命名约定列表

javascript - 尝试 console.log $scope 变量时读取未定义

python - 将两个 LISTS 值的 SUM 添加到新 LIST

javascript - meteor http获取调用

javascript - 当选择其他选择选项时,用变量值更新选择列表?

python - 在numpy中将单个元素添加到数组

c - 初始化二维数组是否适合将连续整数映射到 C 中的字符串?

python - 在 Python 中创建一个具有一定大小的空列表

javascript - 注册成功时PHP HTML警告框

javascript - Create-React-App 在 Edge 浏览器中不起作用