简体   繁体   English

javascript中两个嵌套循环有什么区别?

[英]What is the difference between the two nested loops in javascript?

function a() {
    var n1 = 0,
        n2 = 0;
    for (; n1 < 100; n1++) {
        for (; n2 < 100; n2++) {
            console.log(2);
        }
        console.log(1);
    }
}
a();

function b() {
    for (var n1 = 0; n1 < 100; n1++) {
        for (var n2 = 0; n2 < 100; n2++) {
            console.log(2);
        }
        console.log(1);
    }
}
b();

As you can see.Two simple nested loops,and it looks like they will have the same output.But what puzzles me is that function a() does not output expected result,it loops outside and inside 100 times respectively.What's the difference? 正如你所看到的。两个简单的嵌套循环,看起来它们会有相同的输出。但令我困惑的是函数a()不输出预期的结果,它分别在内外循环100次。有什么区别?

In your b() function n2 variable is created (see @jfriend00 comment) reset during every a loop iteration. 在您的b()函数n2变量被 创建 (见@ jfriend00评论)每期间重置 a循环迭代。 It is set to 0 and therefore the b loop goes the whole length (100 times). 它被设置为0,因此b循环遍及整个长度(100次)。

In a the variable n1 is created once before the inner loop, so after first a iteration (and 100 b ), n2 has a value of 100. In the second a interation n2 is checked if it's less than 100. It's not, so the inner loop ends before it even started. a变量n1在内循环之前创建一次,所以第一后a迭代(和100 b ), n2具有100的值。在第二个a互为作用n2 ,如果它是小于100。这不是被选中,所以内环在它开始之前结束。

First, lets clear up the variable declarations - hoisting and function scope means that both functions look something like this 首先,让我们清理变量声明 - 提升和函数范围意味着两个函数看起来都像这样

function a() {
  var n1;
  var n2;
  n1 = 0;
  n2 = 0;
  for (; n1 < 100; n1++) {
    for (; n2 < 100; n2++) {
        console.log(2);
    }
    console.log(1);
  }
}
a();

function b() {
  var n1;
  var n2;
  for (n1 = 0; n1 < 100; n1++) {
    for (n2 = 0; n2 < 100; n2++) {
        console.log(2);
    }
    console.log(1);
  }
}
b();

Now it should be more obvious - function b sets n2 to zero at the start of every for loop, function a does not. 现在它应该更加明显 - 函数b在每个for循环的开始处将n2设置为零,而函数a则不是。 If this behavior surprises you, then read more about function scope in JavaScript. 如果这种行为让您感到惊讶,那么请阅读JavaScript中有关函数范围的更多信息。

Variable Scope 可变范围

在a()n2中只有一次,但在每次n1改变时b()inited

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM