【问题标题】:Is a variable declared in a for-loop's first statement scoped or treated specially?在 for 循环的第一条语句中声明的变量是作用域还是特殊处理?
【发布时间】:2018-02-25 19:45:04
【问题描述】:

这两个示例之间是否有任何(我的意思是任何)区别,按类型输入 - 甚至是细微的区别?

for (var foo = 0; …; …)
    statement;

var foo = 0;
for (; …; …)
    statement;

我似乎记得我读过的一些评论说它的行为略有不同,但据我所知,foo 在这两种情况下仍然是函数范围的。有什么区别?

(我试图通读ECMA-262 13.7.4,但结果有点过头了。)

【问题讨论】:

  • foo 在这两种情况下仍然是函数作用域,这是正确的。

标签: javascript syntax binding scope specifications


【解决方案1】:

是的,有区别。

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- 如果一个变量从未被赋值,它的值为undefined

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

【讨论】:

  • 你能详细说明最后两个有什么不同吗?
  • 我仍然不明白第三个示例是如何“错误”的。这当然没有错,只是写同一件事的不同方式。
  • @Tomalak 我的意思是错误的假设:有人认为这就是吊装的工作方式是错误的。我会改写评论。
  • 我知道吊装;我非常具体地指的是我输入的示例:在赋值语句和for 语句之间没有语句。我会改进原来的问题,谢谢!
  • @Tomalak OP 说...即使是一个微妙的,所以必须仔细包含细节。声明和for 循环之间没有其他语句的事实使上述所有示例都等效,但实际上它的工作方式只有前两个是等效的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-09-09
  • 2011-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多