我目前正在使用 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/