简体   繁体   English

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

[英]How does a variable as a second statement in a for-loop work?

I tried to find an answer to this question, please forgive me if I am just too stupid to find it.我试图找到这个问题的答案,如果我太愚蠢而无法找到它,请原谅我。 I am sorry if that's the case.如果是这样的话,我很抱歉。 But I have this loop and I have no idea why it does what it does.但是我有这个循环,我不知道它为什么会这样做。 This is an exercise from the book "Eloquent JavaScript" by Marjin Haverbeke (Page 89, if anyone's interested)这是 Marjin Haverbeke 的“Eloquent JavaScript”一书中的一个练习(第 89 页,如果有人感兴趣的话)

My question is how the variable "node" works as a second statement.我的问题是变量“节点”如何作为第二条语句工作。

Any explanation much appreciated!任何解释都非常感谢!

Thanks, Ben谢谢,本

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: [ 'one', 'two', 'three' ] Output:['一','二','三']

I believe you are asking how node works as the second expression inside the for loop.我相信您在问node如何作为for循环中的第二个表达式工作。 Javascript just evaluates that value as true of false, it's like saying !!node . 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);
}

To further explain how for loop works, it consists of three expressions, the initializer, condition (which js will evaluate to true or false), and the final expression.为了进一步解释 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
}


In the second statement of the for loop, you need to provide a condition on which the loop should run or stop.for循环的第二条语句中,您需要提供循环应该运行或停止的条件。 So, it should be something that gives an output of either true or false .因此,它应该给出 output 的truefalse

In this case, node will have some value.在这种情况下, node将具有一定的价值。 That value is evaluated as true if it is anything other than 0 or null .如果该值不是0null ,则该值被评估为true So, when the node.rest returns null .因此,当node.rest返回null时。 The condition will become false .条件将变为false Hence, stopping the loop.因此,停止循环。

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

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