为什么我不必在loop中声明JavaScript中的变量
在JavaScript中,为什么我们能够在for循环中使用尚未声明的变量(即const,Let,var)?下面的示例代码:
function testFunc(items) {
for (item of items) {
console.log(item)
}
}
我希望上述代码会出错。我们不需要用 const 之一,让和 var 关键字来声明变量吗?下面的示例:
function testFunc(items) {
for (const item of items) {
console.log(item)
}
}
in javascript, why are we able to use variables that havent been declared (i.e. const, let, var) in the for loop? example code below:
function testFunc(items) {
for (item of items) {
console.log(item)
}
}
I would expect the above code to error out. Dont we need to declare the variable with one of the const, let and var keywords? Example below:
function testFunc(items) {
for (const item of items) {
console.log(item)
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在非图案模式下,它不会丢失错误。它将为窗口创建一个全局变量
item
:即使您在分配之前无法获得
item
的值(参考eRror),如果您在非图案模式下具有item = 1
之类的分配,它将创建一个变量(全球范围)如果尚未定义。在这种情况下,for循环进行item = 1
,item = 2
,item = 3
。因此,允许获取item
的值item
在循环为3
之后。但是,如果您只添加“使用严格”语句,则会引发错误
In non-strict mode, it will not throw an error. It will just create a global variable
item
for the window:Even though you cannot get the value of
item
before it's assigned (ReferenceError), if you have an assignment likeitem=1
in non-strict mode, it will create a variable (global scope) if it's not yet defined. The for loop in this case does theitem=1
,item=2
,item=3
. So, getting the value of theitem
(as inconsole.log(item)
) is allowed.And as you can see from the output, the value of
item
after the loop is3
.But if you just add a "use strict" statement, it throws an error