How does `for..of` loop resolve the iterator from an object?

后端 未结 2 1105
太阳男子
太阳男子 2021-01-19 17:35

For an object to implement iterable interface it must implement [Symbol.iterator] key that points to a function that returns the iterator. I\'m won

2条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-19 18:21

    The specific place where the operation is specified is in 7.4.1 GetIterator( obj [ , method ] ). This gets the @@iterator property of the passed object in step 1a. of the abstract operation:

    a. Set method to GetMethod(obj, @@iterator).

    @@iterator is a well-known symbol that is the Symbol.iterator property on objects.

    This is used by for-in and for-of loops due to the productions in 13.7.5.11 Runtime Semantics:

    IterationStatement : for(ForDeclaration of AssignmentExpression) Statement

    1. Let keyResult be the result of performing ForIn/OfHeadEvaluation(BoundNames of ForDeclaration, AssignmentExpression, iterate).
    2. Return ForIn/OfBodyEvaluation(ForDeclaration, Statement, keyResult, iterate, lexicalBinding, labelSet).

    Here, you can see the iterator argument passed to ForIn/OfBodyEvaluation is the return value keyResult of ForIn/OfHeadEvaluation. The return value is, in step 7b:

    b. Return GetIterator(exprValue).

    Thus, for-of loops get the iterator by accessing the @@iterator or Symbol.iterator well-known symbol by specification.

提交回复
热议问题