为什么我不必在loop中声明JavaScript中的变量

发布于 2025-01-21 11:08:09 字数 549 浏览 3 评论 0原文

在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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

蓝颜夕 2025-01-28 11:08:09

在非图案模式下,它不会丢失错误。它将为窗口创建一个全局变量item

function testFunc(items) {
    for (item of items) {
        console.log(item)
    }
}
testFunc([1,2,3])
console.log(window.item) //property created in the window object
console.log(item) //global variable

即使您在分配之前无法获得item的值(参考eRror),如果您在非图案模式下具有item = 1之类的分配,它将创建一个变量(全球范围)如果尚未定义。在这种情况下,for循环进行item = 1item = 2item = 3。因此,允许获取item的值item在循环为3之后。


但是,如果您只添加“使用严格”语句,则会引发错误

"use strict"
function testFunc(items) {
    for (item of items) {
        console.log(item)
    }
}
testFunc([1,2,3]) //throws ReferenceError

In non-strict mode, it will not throw an error. It will just create a global variable item for the window:

function testFunc(items) {
    for (item of items) {
        console.log(item)
    }
}
testFunc([1,2,3])
console.log(window.item) //property created in the window object
console.log(item) //global variable

Even though you cannot get the value of item before it's assigned (ReferenceError), if you have an assignment like item=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 the item=1, item=2, item=3. So, getting the value of the item (as in console.log(item)) is allowed.
And as you can see from the output, the value of item after the loop is 3.


But if you just add a "use strict" statement, it throws an error

"use strict"
function testFunc(items) {
    for (item of items) {
        console.log(item)
    }
}
testFunc([1,2,3]) //throws ReferenceError

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文