[英]How does a variable as a second statement in a for-loop work?
我試圖找到這個問題的答案,如果我太愚蠢而無法找到它,請原諒我。 如果是這樣的話,我很抱歉。 但是我有這個循環,我不知道它為什么會這樣做。 這是 Marjin Haverbeke 的“Eloquent JavaScript”一書中的一個練習(第 89 頁,如果有人感興趣的話)
我的問題是變量“節點”如何作為第二條語句工作。
任何解釋都非常感謝!
謝謝,本
list = { value: 'one', rest: { value: 'two', rest: { value: 'three', rest: null }}};
function listToArray(list) {
let array = [];
for (let node = list; node ; node = node.rest) {
array.push(node.value);
}
return array;
}
console.log(listToArray(list));
Output:['一','二','三']
我相信您在問node
如何作為for
循環中的第二個表達式工作。 Javascript 只是將該值評估為真或假,就像說!!node
。
// to simplify the for loop, the variable node starts with the list
// and if the node exists executes the code block inside and continues the loop
// when node.rest becomes null the loop exits
for (let node = list; node ; node = node.rest) {
array.push(node.value);
}
為了進一步解釋 for 循環是如何工作的,它由三個表達式組成,初始化器、條件(js 將評估為真或假)和最終表達式。
for (
let i = 0; // initializes the variable i
i < 10; // condition that determines whether the loop should continue next iteration or not
i++; // final-expression which increments the i variable to be used in the next iteration
) {
// code block
}
在for
循環的第二條語句中,您需要提供循環應該運行或停止的條件。 因此,它應該給出 output 的true
或false
。
在這種情況下, node
將具有一定的價值。 如果該值不是0
或null
,則該值被評估為true
。 因此,當node.rest
返回null
時。 條件將變為false
。 因此,停止循環。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.