为什么嵌套的 Java 脚本循环具有相同的循环计数器名称

why java script nested for loop having loops counter name same goes infinetly

本文关键字:循环 计数器 嵌套 Java 脚本 为什么      更新时间:2023-09-26

以下代码将输出什么。

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

无休止的;)