JavaScript:检查元素列表

JavaScript:检查元素列表,javascript,arrays,list,function,Javascript,Arrays,List,Function,我目前正在使用Marijn Haverbeke的优秀著作《雄辩的JavaScript》学习JavaScript。现在有一个练习,您必须编写一个递归函数,返回嵌套列表的第n个元素。如果没有这样的元素,函数应该返回undefined。解决方案如下所示: function nth(list, n) { if (!list) return undefined; else if (n == 0) return list.value; else return nth(li

我目前正在使用Marijn Haverbeke的优秀著作《雄辩的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);
}
到目前为止,我觉得一切都很清楚。然而,如果(!list){}做了什么,我并没有真正了解
到底做了什么。这种情况是如何评估的?如果
list
有一个元素
n
,为什么是真的

完整的练习可以在这里找到: 这个

if (!list)
是一种简写的表达方式

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

!当列表短于
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'
这个

是一种简写的表达方式

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

!当列表短于
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'
然而,如果(!list){}真的发生了什么,我真的不知道

它检查
列表
变量是否仍然具有非假值的值,例如
null
未定义
0
false
NaN
'
。如果列表有任何错误值,则返回
未定义的

如果列表中有一个元素n,为什么是真的

根据您共享的链接,列表的值为

var list = {
  value: 1,
  rest: {
    value: 2,
    rest: {
      value: 3,
      rest: null
    }
  }
};
这意味着
rest
有子元素,或者它有
null

最终,它将具有
null
,这就是此条件将断言并返回
undefined

然而,如果(!list){}真的发生了什么,我真的不知道

它检查
列表
变量是否仍然具有非假值的值,例如
null
未定义
0
false
NaN
'
。如果列表有任何错误值,则返回
未定义的

如果列表中有一个元素n,为什么是真的

根据您共享的链接,列表的值为

var list = {
  value: 1,
  rest: {
    value: 2,
    rest: {
      value: 3,
      rest: null
    }
  }
};
这意味着
rest
有子元素,或者它有
null


最后,如果(!list)
检查空值,它将具有
null
,这就是此条件将断言并返回
undefined

list@FrédéricHamidi是的,列表分支,因为如果(!list)
检查空的list@Fr是的,名单分支,因为它是递归遍历的
list==NaN
总是
false
@MaxZuber-wups。已修复。
isNan(list)
列表
强制转换为数字类型,因此会导致意外结果。使用
列表!==list
而不是
list===NaN
始终
false
@MaxZuber-wups。已修复。
isNan(list)
列表
强制转换为数字类型,因此会导致意外结果。使用
列表!==列表
而不是