Javascript: When writing a for loop, why does it print the last index number?

自作多情 提交于 2019-11-28 09:43:47

问题


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; ++i) { numbers[i]=i+1; }
100
js> i
100

Can someone please explain why the interpreter works like that? I didn't explicitly ask it to print the value of i.

Sorry for the ambiguous formulation, guys, but I didn't really know how to describe what's happening.


回答1:


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; }')



来源:https://stackoverflow.com/questions/23446706/javascript-when-writing-a-for-loop-why-does-it-print-the-last-index-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!