gpt4 book ai didi

JavaScript:检查列表中的元素

转载 作者:行者123 更新时间:2023-12-02 14:25:53 26 4
gpt4 key购买 nike

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com