虽然 x 不是常量,但以下代码如何运行而不会出现任何错误?
for (const x of [1,2,3]){
console.log(x);
}
最佳答案
它适用于 Chrome 等兼容浏览器,因为它们会在每次迭代时创建一个新的、不同的常量变量:
var arr = [];
for (const x of [1,2,3])
arr.push(() => x);
arr.map(f => f()); // [1,2,3] on Chrome
一些不兼容的浏览器会重用相同的变量:
var arr = [];
for (let x of [1,2,3])
arr.push(() => x);
arr.map(f => f()); // [3,3,3] on non-compliant browsers
因此,如果在上面的示例中使用 const
,它们会抛出错误。
Runtime Semantics: ForIn/OfBodyEvaluation说:
- Repeat
- Else
- Assert: lhsKind is lexicalBinding.
- Assert: lhs is a ForDeclaration.
- Let iterationEnv be NewDeclarativeEnvironment(oldEnv).
- Perform BindingInstantiation for lhs passing iterationEnv as the argument.
所以每次迭代都应该创建一个新的绑定(bind)。 Chrome 是正确的。
关于javascript - 在 es6 for of 循环中使用 const,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36684191/