English 中文(简体)
为什么全局和块范围的变量返回不同的i值?
原标题:Why do global and block scoped variables return different values of i?

https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/es6/compare-scopes-of-the-var-and-let-keywords

var printNumTwo;
for (var i = 0; i < 3; i++) {
  if (i === 2) {
    printNumTwo = function() {
      return i;
    };
  }
}
console.log(printNumTwo());

这会将3打印到控制台。

let printNumTwo;
for (let i = 0; i < 3; i++) {
  if (i === 2) {
    printNumTwo = function() {
      return i;
    };
  }
  console.log(i);
}
console.log(printNumTwo());
//console.log(i);

这会将2打印到控制台。我还添加了console.log(I);以在整个循环中调试和检查i的值,并在i==2处结束。当i==2时,循环是否退出?我想我会迭代到3,然后当条件I<;3为假,也就是当i==3时。

为什么在第一个例子中我以3结尾,在第二个例子中以2结尾?

问题回答

在第一个示例中,使用var关键字声明变量i,循环运行三次迭代,其中i为0、1和2。当i为2时,条件i===2为true,并且函数printNumTwo被分配了一个闭包,该闭包捕获i在该时刻的值,即2。但是,var关键字具有函数作用域,而不是块作用域。这意味着变量i在循环的所有迭代中都是共享的。循环结束后,i的值为3,因为当循环条件i<;3变为假并且循环退出。当您调用printNumTwo()时,它会返回i的当前值,即3。

在第二个示例中,使用let关键字声明变量i,循环还运行三次迭代,其中i为0、1和2。然而,let具有块范围,这意味着在循环的每次迭代中都会创建一个新的i变量。当i为2时,条件i===2为true,并且函数printNumTwo被分配了一个闭包,该闭包捕获该特定迭代中i变量的值,即2。由于i是用let声明的,因此函数内部的i不受循环迭代中的变化的影响。当您调用printNumTwo()时,它会返回捕获的值,即2。

因此,这两个例子之间的区别在于i变量的范围。在第一个例子中,i在所有迭代中共享,并被修改,直到循环退出时它变为3。在第二个例子中,每个迭代都有自己的独立i变量,具有不同的范围,并且函数中捕获的i值保持为2。





相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签