`for..of`循环如何解析对象的迭代器? [英] How does `for..of` loop resolve the iterator from an object?
问题描述
对于实现可迭代接口的对象,它必须实现 [Symbol.iterator]
键,该键指向返回迭代器的函数
。我想知道 for..of
循环内部是否在一个对象上调用此方法来获取 iterator
?
For an object to implement iterable interface it must implement [Symbol.iterator]
key that points to a function that returns the iterator
. I'm wondering if the for..of
loop internally calls this method on an object to get that iterator
?
我很好奇的原因是,例如, Map
定义了一个带有几个迭代器的接口(条目,值,键)似乎如果没有明确指定, for..of
循环使用 map.entries()返回的迭代器
打电话。
The reason I'm curious is that, for example, Map
defines an interface with several iterators (entries, values, keys) and it seems that if not specified explicitly the for..of
loop uses the iterator returned by map.entries()
call.
我正在尝试搜索在规范中但它只指定 iterator
作为参数传递给抽象操作 ForOf
:
I've trying searching in the specification but it only specifies that iterator
is passed as a parameter to the abstract operation ForOf
:
使用参数
lhs,stmt, iterator ,iterationKind,lhsKind和labelSet调用抽象操作ForIn / OfBodyEvaluation。
The abstract operation ForIn/OfBodyEvaluation is called with arguments lhs, stmt, iterator, iterationKind, lhsKind, and labelSet.
所以基本上有两个问题:
So basically two questions:
- 如何从对象中获取迭代器?
- 在哪里指定规范?
推荐答案
指定操作的具体位置在 7.4.1 GetIterator(obj [,method])。这将获取步骤1a中传递的对象的 @@ iterator
属性。抽象操作:
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。将方法设置为 GetMethod ( obj ,@@ iterator)。
a. Set method to GetMethod(obj, @@iterator).
@@ iterator
是众所周知的符号,即对象上的 Symbol.iterator
属性。
@@iterator
is a well-known symbol that is the Symbol.iterator
property on objects.
这是使用的由于 13.7.5.11运行时语义:
IterationStatement :for( ForDeclaration of AssignmentExpression ) Statement
IterationStatement : for(ForDeclaration of AssignmentExpression) Statement
- 让 keyResult 成为执行 ForIn / OfHeadEvaluation (的BoundNames ForDeclaration , AssignmentExpression ,iterate)。
- 返回 ForIn / OfBodyEvaluation ( ForDeclaration , Statement , keyResult ,iterate,lexicalBinding, labelSet )。
- Let keyResult be the result of performing ForIn/OfHeadEvaluation(BoundNames of ForDeclaration, AssignmentExpression, iterate).
- Return ForIn/OfBodyEvaluation(ForDeclaration, Statement, keyResult, iterate, lexicalBinding, labelSet).
在这里,您可以看到传递给 ForIn / OfBodyEvaluation 是返回值 keyResult ForIn / OfHeadEvaluation 。返回值在步骤7b中:
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。返回 GetIterator ( exprValue )。
因此,for-of循环通过访问 @@ iterator <来获取迭代器/ code>或
Symbol.iterator
按规范说明的已知符号。
Thus, for-of loops get the iterator by accessing the @@iterator
or Symbol.iterator
well-known symbol by specification.
这篇关于`for..of`循环如何解析对象的迭代器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!