JavaScript 循环变量作用域

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18465211/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 12:01:42  来源:igfitidea点击:

JavaScript loop variable scope

javascriptvariablesfor-loopscope

提问by BlackBox

Just a quick question about the scoping of JavaScript variables.

只是一个关于 JavaScript 变量范围的快速问题。

Why does the alert()function print the value of iinstead of returning undefined?

为什么该alert()函数打印的值i而不是返回值undefined

$(document).ready(function () {
    for(var i = 0; i < 10; i += 1){
    }

     alert("What is 'i'? " + i);
});

I'm fairly new to JS, and in nearly all other languages I've dabbled, a declaration in the scope of the for loop would contain the value to that said loop, but not in this case, why?

我对 JS 相当陌生,在我涉足过的几乎所有其他语言中,for 循环范围内的声明将包含该循环的值,但在这种情况下不是,为什么?

i.e. What is 'i'? 10'is printed.

What is 'i'? 10'打印。

回答by insertusernamehere

See the MDN for the "initialization parameters" of a for-loop:

有关-loop的“初始化参数”,请参阅 MDN :for

An expression (including assignment expressions) or variable declaration. Typically used to initialize a counter variable. This expression may optionally declare new variables with the var keyword. These variables are not local to the loop, i.e. they are in the same scope the for loop is in.The result of this expression is discarded.

表达式(包括赋值表达式)或变量声明。通常用于初始化计数器变量。此表达式可以选择使用 var 关键字声明新变量。这些变量不是循环的局部变量,即它们在 for 循环所在的同一范围内。该表达式的结果被丢弃。

回答by BlackBox

JavaScript didn't have block scope until constand letwere introduced, just varwhich is function scoped. Since the initialization of iis within one function, that variable is accessible anywhere else in that same function.

JavaScript 在constlet被引入之前没有块作用域,只是var函数作用域。由于 的初始化i在一个函数内,该变量可在同一函数中的任何其他地方访问。

From MDN:

来自MDN

Important: JavaScript does not have block scope. Variables introduced with a block are scoped to the containing function or script, and the effects of setting them persist beyond the block itself. In other words, block statements do not introduce a scope. Although "standalone" blocks are valid syntax, you do not want to use standalone blocks in JavaScript, because they don't do what you think they do, if you think they do anything like such blocks in C or Java.

重要提示:JavaScript 没有块作用域。块中引入的变量的作用域是包含函数或脚本,并且设置它们的效果在块本身之外持续存在。换句话说,块语句不引入作用域。尽管“独立”块是有效的语法,但您不希望在 JavaScript 中使用独立块,因为如果您认为它们在 C 或 Java 中执行此类块,则它们不会执行您认为它们所做的事情。

回答by Matt Coarr

The javascript folks are trying to fix this!

javascript 人员正试图解决这个问题!

EcmaScript6 (aka EcmaScript 2015) is the latest version of javascript that was passed last summer and browsers are just starting to support its features.

EcmaScript6(又名 EcmaScript 2015)是去年夏天通过的最新版本的 javascript,浏览器才刚刚开始支持其功能。

One of those features is block-scope local variables with the "let" expression. As of right now (April 2016), most of the current versions of the major browsers support this except Safari. Few mobile browsers support this.

其中一项功能是具有“let”表达式的块范围局部变量。截至目前(2016 年 4 月),除 Safari 外,大多数当前版本的主要浏览器都支持此功能。很少有移动浏览器支持这一点。

You can read more about it here (in particular, see the section "let-scoped variables in for loops"): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let

您可以在此处阅读有关它的更多信息(特别是,请参阅“for 循环中的 let 范围变量”部分):https: //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let

You can check current browser support here (look for the row Bindings -> let): https://kangax.github.io/compat-table/es6/

您可以在此处检查当前浏览器支持(查找行 Bindings -> let):https: //kangax.github.io/compat-table/es6/

回答by Hitesh Kumar

Unlike other languages (for example: Java, C++, C), JavaScript doesn't support block scope. Once you declare a variable in a loop or in a function it's scope is within the function body if you do

与其他语言(例如:Java、C++、C)不同,JavaScript 不支持块作用域。一旦你在循环或函数中声明了一个变量,它的作用域就在函数体内,如果你这样做了

for(i=0; i<arr.length; i++) {
    var j=0;
    // ...
}

here your ibecomes a global variable and jbecome local to the function or script in which the loop is.

在这里,您i将成为一个全局变量,并j成为循环所在的函数或脚本的局部变量。

回答by Matt Smith

for(i=0; i<arr.length; i++) {
    var j=0;
    // ...
}

it is not correct to state that the above creates a global variable i. I believe you should always use varto declare variables (unless you are intentionally wanting a 'property' rather than a 'variable' -which is pretty unlikely in 99.99% of JS coding scenarios ...)

说上面创建了一个全局变量是不正确的i。我相信你应该总是使用var来声明变量(除非你是故意想要一个“属性”而不是一个“变量”——这在 99.99% 的 JS 编码场景中是不太可能的......)

Omitting varwhen assigning an initial value to iisn't creating a local or even a global variable, it is creating a property ifor the global object (which may seem/behave mostly like a global variable - but they have some subtle differences).

var在分配初始值时省略i不是创建局部变量,甚至不是全局变量,而是为i全局对象创建一个属性(它可能看起来/行为大多像一个全局变量 - 但它们有一些细微的区别)。

better would be:

更好的是:

var i;
for(i=0; i<arr.length; i++) {
    var j=0;
    // ...
}

now the loop is using a global variable i(or function local variable i, if this code appears in a function)

现在循环正在使用全局变量i(或函数局部变量i,如果此代码出现在函数中)

see more about this at what is function of the var keywordand variables vs. properties in Javascript

在 Javascript 中var 关键字变量与属性的作用是什么,了解更多相关信息

-- note, what is a little confusing is that you can re-declare a variable, for example in a second loop

-- 请注意,有点令人困惑的是您可以重新声明一个变量,例如在第二个循环中

for(var i=0; i<9; i++){
    document.write('i = ' + i + '<br>');
}


for(var i=0; i<9; i++){
    document.write('i = ' + i + '<br>');
}

this seems to be valid (no errors when I test). It seems that you CAN re-declare variables in JavaScript - but it probably isn't every a good idea, unless a special case - see this related question mentioning how [Google Analytics makes use of the 'safe' redeclaration of a variable] (Redeclaring a javascript variable)

这似乎是有效的(我测试时没有错误)。似乎您可以在 JavaScript 中重新声明变量 - 但它可能不是一个好主意,除非特殊情况 - 请参阅此相关问题,其中提到 [Google Analytics 如何使用变量的“安全”重新声明](重新声明一个 javascript 变量

there is some discussion about re-declaring variables in JS (and also loop variables like i) in this related SO question: declare variables inside or outside the loop

i在这个相关的 SO 问题中,有一些关于在 JS 中重新声明变量(以及循环变量,如)的讨论:在循环内部或外部声明变量

There is event a JavaScript pattern for single declaration of variables

有一个用于单个变量声明的 JavaScript 模式事件