请考虑以下代码段
var a = [1, 2, 3, 4];
for (a of a) { // The first 'a' is made by mistake
console.log(a);
}
Run Code Online (Sandbox Code Playgroud)
第一次a在for环被错误写入.我认为上面的代码应该运行错误,因为在第一次迭代中a分配时1,则a不是可迭代对象.所以在下一次迭代中应该抛出一个错误.
实际上,结果如下:
1
2
3
4
Run Code Online (Sandbox Code Playgroud)
看来上面的代码可以正确地迭代数组.在后for循环,结果a是4.为什么?
> a
4
Run Code Online (Sandbox Code Playgroud)
为了进一步调查,我试图从中找到一些信息ECMA-6 doc,但我对以下声明感到困惑.
for(VAR ForBinding of AssignmentExpression)语句
for(ForDeccration of AssignmentExpression)声明
要理解ForBinding和ForDeclaration,请测试以下代码.
var a = [1, 2, 3, 4];
for (var a of a) {
console.log(a);
}
console.log(a);
Run Code Online (Sandbox Code Playgroud)
不幸的是,结果与之前的代码相同.for (var a in a)和之间有什么区别for (a in a)?
for评估"AssignmentExpression"的值并迭代它.该值仅在迭代开始时获得一次,因此重用相同的变量是完全有效的(也非常令人困惑).
的存在var:for (a of ...)并for (var a of ...)没有任何1个中的代码差异,你已经a确定-所以它只是重新申报相同的变量.
为了完全精确,有些行为是不同的 - 当a在外部作用域中声明当前函数var版本时会影响该值(如在JavaScript中所有var语句都被提升到函数作用域的顶部):
var a = [1,2,3];
function tryForVar() {
// Note that declaration of `a` is hoisted here as var a = undefined;
// for (var a ... does not work as expected as local 'a' is undefined
for (var a of a) {
console.log(a); // log 'undefined' once
}
console.log(a); // undefined
}
tryForVar();
console.log(a); // [1,2,3]
function tryFor() {
// Note that declaration of `a` from outer scope
// for (a ... works fine as it uses outer 'a'
for (a of a) {
console.log(a); // logs all 1,2,3 in sequence
}
console.log(a); // 3
}
tryFor();
console.log(a); // 3
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
269 次 |
| 最近记录: |