这两个示例之间是否存在任何(我的意思是任何)差异,就像键入的那样 - 即使是细微的差异?
for (var foo = 0; …; …)
statement;
和
var foo = 0;
for (; …; …)
statement;
我似乎记得我读过的一些评论,它的行为略有不同,但据我所知, foo
在这两种情况下仍然是函数范围的。有什么区别?
(我试图通读 ECMA-262 13.7.4 ,但最终有点超出了我的理解范围。)
最佳答案
是的,有区别。
for (var foo = something; …; …)
statement;
相当于:
var foo; // hoist foo (declare it at top)
for (foo = something; …; …) // but doesn't assign the value at top, it will assign it where it was before the hoisting
statement;
但不等于:
var foo = something; // wrong assumption: it should not move the assignemet to top too, it should move just the declaration
for (; …; …)
statement;
证明:
1-
如果未声明变量,则会抛出错误:
console.log(foo);
2-
如果变量从未被赋值,则其值为未定义
:
var foo;
console.log(foo);
3-
将声明移动到顶部(提升),但不移动赋值:
console.log(foo); // undefined value but doesn't throw an error
var foo = "Hello, world!";
所以它相当于:
var foo; // declared first so it doesn't throw an error in the next line
console.log(foo); // undefined so the assignment is still after this line (still at the same place before hoisting)
var foo = "Hello, world!"; // assignment here to justify the logged undefined value
关于javascript - for 循环的第一个语句中声明的变量是否有作用域或经过特殊处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46259509/