0

我想知道为什么我们const在 javascriptfor...of循环中使用。我看到的每个使用for...of循环的示例都const在声明变量时使用。例如:

for (const item of array) {
    // do something
}

我们有什么理由不这样使用var吗?

for (var item of array) {
    // do something
}

谢谢

4

1 回答 1

2

var将变量加载到全局作用域中,而letandconst将在词法作用域中声明它:

const test = [1, 2, 3];

// lexical
for (let testItem of test) {
    console.log(window.testItem);
}

// global
for (var testItem of test) {
    console.log(window.testItem);
}

于 2020-07-03T17:16:22.647 回答