为什么嵌套的 Java 脚本循环具有相同的循环计数器名称
why java script nested for loop having loops counter name same goes infinetly
以下代码将输出什么。
for(var i=0; i<5; i++){
for(var i=0; i<3; i++){
console.log(i + ' ' + i);
}}
为什么是无限循环。
那是因为你使用i
两次,所以每次进入第二个循环时,你都会将i重置为0。
您的代码应该是:
for(var i=0; i<5; i++){
for(var j=0; j<3; j++){
console.log(i + ' ' + j);
}}
因为每次迭代外循环,内循环都会将 i 重置为 0。 它永远不会达到 5。
for(var i=0; i<5; i++){
// will be 4 here then reset to 0 it will only ever make it to 4 never reach 5.
for(var i=0; i<3; i++){
console.log(i + ' ' + i);
}}
这是因为当你以 0 进入第一个循环时,您将 i 重置为 0,当您的 i 变为 3 时,您从内部循环出来并进入 4 的外部循环,然后再次重置为 0 并进入循环。
您可以使用两个不同的变量来解决问题,例如:
for(var i=0; i<5; i++) {
for(var j=0; j<3; j++) {
console.log(i + ' ' + j);
}
}
由于var
声明将被提升到范围的顶部(我不打算详细说明原因),因此代码最终将像这样运行:
var i;
for(i = 0; i < 5; i++
{
for(i = 0; i < 3; i++)
{
}
}
您认为远循环会创建一个新的"代码块"(Scope),但事实并非如此。如果你要这样做:
for(var i = 0; i < 5; i++)
{
+function() {
for(var i = 0; i < 3; i++
{
}
}();
}
然后它会按照你认为它现在会工作的方式工作,但你不应该。您应该只使用 2 个不同的变量。
1st iteration of loop #1
starts with i = 0
1st iteration of loop #2
starts with i = 0
ends with i = 1
2nd iteration of loop #2
starts with i = 1
ends with i = 2
3rd iteration of loop #2
starts with i = 2
ends with i = 3
ends with i = 4
2nd iteration of loop #1
starts with i = 4
1st iteration of loop #2
starts with i = 0
ends with i = 1
2nd iteration of loop #2
starts with i = 1
ends with i = 2
3rd iteration of loop #2
starts with i = 2
ends with i = 3
ends with i = 4
3nd iteration of loop #1
starts with i = 4
1st iteration of loop #2
starts with i = 0
ends with i = 1
2nd iteration of loop #2
starts with i = 1
ends with i = 2
3rd iteration of loop #2
starts with i = 2
ends with i = 3
ends with i = 4
无休止的;)
相关文章:
- 如何在for循环中使用计数器
- 函数式编程 - 用于递增计数器的简单 for 循环
- 循环的Javascript中的PHP计数器
- 访问带有 for 循环中的计数器的数组
- alert-1,而不是循环中各自的计数器
- 使用{{render}}进行渲染时的循环计数器
- for 循环中 setInterval 中计数器变量 i 的作用域
- 在对象中查找值时,对于循环计数器
- 启动和停止循环计数器 JavaScript
- 为什么嵌套的 Java 脚本循环具有相同的循环计数器名称
- ajax调用的循环-访问循环计数器
- 函数调用中的循环计数器可视性
- 在循环之后访问for循环计数器是否安全
- 为什么 for 循环计数器在 javascript 中退出循环后不会被销毁
- jQuery模板循环计数器
- 如何将循环计数器作为对象属性传递
- For在twig.js中循环,设置循环计数器
- 使用循环计数器如何动态创建对象并在命名对象时使用计数器
- 如何使用循环计数器修改超链接构造函数的值
- Javascript for循环计数器作为字符串输出