javascript - for 循环的第一个语句中声明的变量是否有作用域或经过特殊处理?

标签 javascript syntax binding scope specifications

这两个示例之间是否存在任何(我的意思是任何)差异,就像键入的那样 - 即使是细微的差异?

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/

相关文章:

javascript - 将 Hammer.js 触摸手势与 jQuery SVG 缩放库集成

java - 为什么 Java 不允许在迭代器上使用 foreach(仅在可迭代对象上)?

perl - 在双引号内打印数组

python - 在 Python 的 For 循环中绑定(bind) keyboard.on_press_key

带有格式的 WPF 文本框绑定(bind)

javascript - 一张一张地创建和显示图像作为背景图像 - JavaScript

java - 聚焦文本字段

javascript - C#:基于 .NET 的网络浏览器不显示图像

javascript - 类作用域中的变量赋值在 React 中有效,但在 ES6 中无效

android - MVV交叉: Pass an enum value as a CommandParameter for Android