Javascript:写一个for循环时,为什么会打印最后一个索引号? [英] Javascript: When writing a for loop, why does it print the last index number?

查看:155
本文介绍了Javascript:写一个for循环时,为什么会打印最后一个索引号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当在js解释器中编写一个简单的for循环时,我会自动获得最后一个索引号(在本例中为i)的值。

  JS> for(var i = 0; i <100; ++ i){numbers [i] = i + 1; } 
100
js>我可以解释为什么口译员是这样工作的吗?我没有明确地要求它打印出我的价值。

对于模棱两可的表述抱歉,伙计们,但我真的不知道如何描述发生的事情。

解决方案

javascript中的所有语句都有一个值,包括在循环结构中执行的块。一旦循环块被执行,返回最终值(如果没有操作发生,则返回 undefined )。隐含地提供返回值100的语句是 numbers [i] = i + 1; ,因为i + 1的最后一次迭代产生100并且赋值操作返回

console.log(hello =World); //输出'World'



现在,这并不是说您可以将for循环的结果赋值给变量,解释器会看到返回值并将其打印到控制台。



我还会补充说这是运行 eval的结果在您的代码:

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


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.

解决方案

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

这篇关于Javascript:写一个for循环时,为什么会打印最后一个索引号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆