繁体   English   中英

变量作为 for 循环中的第二条语句如何工作?

[英]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 的truefalse

在这种情况下, node将具有一定的价值。 如果该值不是0null ,则该值被评估为true 因此,当node.rest返回null时。 条件将变为false 因此,停止循环。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM