[removed] When writing a for loop, why does it print the last index number?

后端 未结 1 1995
温柔的废话
温柔的废话 2020-12-21 16:03

When writing a simple for loop in the js interpreter, I automatically get the last value the index number (i, in this case).

js> for (var i=0; i<100; +         


        
相关标签:
1条回答
  • 2020-12-21 16:37

    All statements in javascript have a value, including the block executed in looping constructs. Once the loop block is executed, the final value is returned (or undefined if no operations take place). The statement that is implicitly providing the return value "100" is numbers[i] = i+1;, as the final iteration of i+1 produces 100 and assignment operations return the value being assigned.

    console.log(hello = "World"); // outputs 'World'

    Now, this is not to say that you can assign the result of a for loop to a variable, but the interpreter "sees" the return value and prints it to the console for you.

    I will also add that it is the result of running eval on your code:

    eval('numbers = []; for(var i = 0; i < 100; i++){ numbers[i] = i+1; }')

    0 讨论(0)
提交回复
热议问题