I have tried the code below in Firefox and Chrome:
function test() {
console.log("***")
return [1,2,3]
}
for (const t of test()) {
console.log(t)
}
The test
function was called only once. Is it the standard behavior for this kind of loop? Is it like the initialization part of for ([initialization]; [condition]; [final-expression])
loop? I didn't find the explanation on MDN and I didn't understand much from ECMA standard.
CodePudding user response:
The ECMAScript specification splits the runtime semantics of the for..in
and for..of
construct into two parts:
ForInOfStatement :
for
(
LeftHandSideExpressionof
AssignmentExpression)
Statement
- Let keyResult be ? ForIn/OfHeadEvaluation(« », AssignmentExpression, iterate).
- Return ? ForIn/OfBodyEvaluation(LeftHandSideExpression, Statement, keyResult, iterate, assignment, labelSet).
So we first have the "head" evaluation (involving the "AssignmentExpression" at the right of of
), and after that, the "body" evaluation, which uses the keyResult (not the AssignmentExpression).
The "head" evaluation involves the actual evaluation in step 3 of that procedure:
- Let exprRef be the result of evaluating expr.
The "body" evaluation involves the actual iteration in step 6:
- Repeat