gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 19:02:02 24 4
gpt4 key购买 nike

这两个示例之间是否存在任何(我的意思是任何)差异,如键入的那样——甚至是细微的差异?

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

关于javascript - 在 for 循环的第一个语句中声明的变量是否有作用域或特殊处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46259509/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com