简体   繁体   中英

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)

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' ]

I believe you are asking how node works as the second expression inside the for loop. Javascript just evaluates that value as true of false, it's like saying !!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 (
  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. So, it should be something that gives an output of either true or false .

In this case, node will have some value. That value is evaluated as true if it is anything other than 0 or null . So, when the node.rest returns null . The condition will become false . Hence, stopping the loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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