簡體   English   中英

JavaScript:檢查元素列表

[英]JavaScript: Checking a list for elements

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

當列表短於n元素時, !list將發生。

// 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){}可以得到,我並沒有真正得到。

它檢查list變量是否仍然具有除假值以外的其他值,例如nullundefined0falseNaN""'' 如果列表具有任何falsey值,則返回undefined

如果list包含元素n,為什么會如此呢?

根據您共享的鏈接,列表的值為

var list = {
  value: 1,
  rest: {
    value: 2,
    rest: {
      value: 3,
      rest: null
    }
  }
};

這意味着rest要么具有子元素,要么具有null

最終,它將具有null ,這是此條件將斷言並返回undefined條件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM