简体   繁体   English

for…of循环完成后,变量的值是多少?

[英]What is the value of the variable after a for…of loop completes?

I have an application for using the final value of an array as the default. 我有一个使用数组的最终值作为默认值的应用程序。 I tried: 我试过了:

x = [1, 2, 3];
for (var zz of x) {};
console.log(zz);   // 3

This is exactly what I wanted, but I was wondering if this is defined behavior of a for...of loop or just a fortuitous result of the implementation. 这正是我想要的,但是我想知道这是否是for ... of循环的定义行为,或者仅仅是实现的偶然结果。 I couldn't find the answer, so was hoping someone here could answer that (preferably with a reference). 我找不到答案,所以希望这里的人可以回答这个问题(最好是提供参考)。

Clarification: The answers and comments thus far are a bit off point. 澄清:到目前为止的答案和评论有点离题。 The example above shows that the final value is, in fact the last value of the array. 上面的示例显示最终值实际上是数组的最后一个值。 My question is that just an unspecified result of the implementation of the formal definition of the for..of loop, or part of the formal definition. 我的问题是for..of循环的正式定义或正式定义的一部分执行的未指定结果。

zz is declared using var , so it is "hoisted" . zz是使用var声明的,因此被“提升” This means that the scope extends outside of the for loop. 这意味着作用域扩展到for循环之外。

Since 3 was assigned to zz at the end, zz will be 3 when the loop finishes. 由于3被分配到zz底, zz3当循环结束。

I think what I was looking for was in the ECMA spec . 我认为我正在寻找的是ECMA规范 The use case is in 13.7.5.11: 用例在13.7.5.11中:

IterationStatement : for ( var ForBinding of AssignmentExpression ) Statement
    1. Let keyResult be the result of performing ? ForIn/OfHeadEvaluation(« »,  AssignmentExpression, iterate).
    2. Return ? ForIn/OfBodyEvaluation(ForBinding, Statement, keyResult, iterate, varBinding, labelSet).

When you slog through 13.7.5.12-13, with those parameters, it appears boil down to everyone's observation (though maybe not quite as obvious as a = 5:-). 当您通过13.7.5.12-13苦干,与那些参数,它似乎归结到每个人的观察(尽管也许并不 A = 5 :-)明显。 So check to jh314 for saying that first. 因此,请先向jh314确认。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM