Iteration protocols - JavaScript 编辑
As a couple of additions to ECMAScript 2015, Iteration protocols aren't new built-ins or syntax, but protocols. These protocols can be implemented by any object by following some conventions.
There are two protocols: The iterable protocol and the iterator protocol.
The iterable protocol
The iterable protocol allows JavaScript objects to define or customize their iteration behavior, such as what values are looped over in a for...of
construct. Some built-in types are built-in iterables with a default iteration behavior, such as Array
or Map
, while other types (such as Object
) are not.
In order to be iterable, an object must implement the @@iterator
method, meaning that the object (or one of the objects up its prototype chain) must have a property with a @@iterator
key which is available via constant Symbol.iterator
:
Property | Value |
---|---|
[Symbol.iterator] | A zero-argument function that returns an object, conforming to the iterator protocol. |
Whenever an object needs to be iterated (such as at the beginning of a for...of
loop), its @@iterator
method is called with no arguments, and the returned iterator is used to obtain the values to be iterated.
Note that when this zero-argument function is called, it is invoked as a method on the iterable object. Therefore inside of the function, the this
keyword can be used to access the properties of the iterable object, to decide what to provide during the iteration.
This function can be an ordinary function, or it can be a generator function, so that when invoked, an iterator object is returned. Inside of this generator function, each entry can be provided by using yield
.
The iterator protocol
The iterator protocol defines a standard way to produce a sequence of values (either finite or infinite), and potentially a return value when all values have been generated.
An object is an iterator when it implements a next()
method with the following semantics:
Property | Value |
---|---|
next() | A zero-argument function that returns an object with at least the following two properties:
The |
Note: It is not possible to know reflectively whether a particular object implements the iterator protocol. However, it is easy to create an object that satisfies both the iterator and iterable protocols (as shown in the example below).
Doing so allows an iterator to be consumed by the various syntaxes expecting iterables. Thus, it is seldom useful to implement the Iterator Protocol without also implementing Iterable.
// Satisfies both the Iterator Protocol and Iterable
let myIterator = {
next: function() {
// ...
},
[Symbol.iterator]: function() { return this; }
};
However, when possible, it's better for iterable[Symbol.iterator]
to return different iterators that always start from the beginning, like Set.prototype[@@iterator]()
does.
Examples using the iteration protocols
A String
is an example of a built-in iterable object:
let someString = 'hi';
console.log(typeof someString[Symbol.iterator]); // "function"
String
's default iterator returns the string's code points one by one:
let iterator = someString[Symbol.iterator]();
console.log(iterator + ''); // "[object String Iterator]"
console.log(iterator.next()); // { value: "h", done: false }
console.log(iterator.next()); // { value: "i", done: false }
console.log(iterator.next()); // { value: undefined, done: true }
Some built-in constructs—such as the spread syntax—use the same iteration protocol under the hood:
console.log([...someString]); // ["h", "i"]
You can redefine the iteration behavior by supplying our own @@iterator
:
// need to construct a String object explicitly to avoid auto-boxing
let someString = new String('hi');
someString[Symbol.iterator] = function () {
return {
// this is the iterator object, returning a single element (the string "bye")
next: function () {
return this._first ? {
value: 'bye',
done: (this._first = false)
} : {
done: true
}
},
_first: true
};
};
Notice how redefining @@iterator
affects the behavior of built-in constructs that use the iteration protocol:
console.log([...someString]); // ["bye"]
console.log(someString + ''); // "hi"
Iterable examples
Built-in iterables
String
, Array
, TypedArray
, Map
, and Set
are all built-in iterables, because each of their prototype objects implements an @@iterator
method.
User-defined iterables
You can make your own iterables like this:
let myIterable = {};
myIterable[Symbol.iterator] = function* () {
yield 1;
yield 2;
yield 3;
};
console.log([...myIterable]); // [1, 2, 3]
Built-in APIs accepting iterables
There are many APIs that accept iterables. Some examples include:
new Map([[1, 'a'], [2, 'b'], [3, 'c']]).get(2); // "b"
let myObj = {};
new WeakMap([
[{}, 'a'],
[myObj, 'b'],
[{}, 'c']
]).get(myObj); // "b"
new Set([1, 2, 3]).has(3); // true
new Set('123').has('2'); // true
new WeakSet(function* () {
yield {}
yield myObj
yield {}
}()).has(myObj); // true
See also
Syntaxes expecting iterables
Some statements and expressions expect iterables, for example the for...of
loops, the spread operator), yield*
, and destructuring assignment
:
for (let value of ['a', 'b', 'c']) {
console.log(value);
}
// "a"
// "b"
// "c"
console.log([...'abc']); // ["a", "b", "c"]
function* gen() {
yield* ['a', 'b', 'c'];
}
console.log(gen().next()); // { value: "a", done: false }
[a, b, c] = new Set(['a', 'b', 'c']);
console.log(a); // "a"
Non-well-formed iterables
If an iterable's @@iterator
method doesn't return an iterator object, then it's considered a non-well-formed iterable.
Using one is likely to result in runtime errors or buggy behavior:
let nonWellFormedIterable = {};
nonWellFormedIterable[Symbol.iterator] = () => 1;
[...nonWellFormedIterable]; // TypeError: [] is not a function
Iterator examples
Simple iterator
function makeIterator(array) {
let nextIndex = 0
return {
next: function() {
return nextIndex < array.length ? {
value: array[nextIndex++],
done: false
} : {
done: true
};
}
};
}
let it = makeIterator(['yo', 'ya']);
console.log(it.next().value); // 'yo'
console.log(it.next().value); // 'ya'
console.log(it.next().done); // true
Infinite iterator
function idMaker() {
let index = 0;
return {
next: function() {
return {
value: index++,
done: false
};
}
};
}
let it = idMaker();
console.log(it.next().value); // '0'
console.log(it.next().value); // '1'
console.log(it.next().value); // '2'
// ...
With a generator
function* makeSimpleGenerator(array) {
let nextIndex = 0;
while (nextIndex < array.length) {
yield array[nextIndex++];
}
}
let gen = makeSimpleGenerator(['yo', 'ya']);
console.log(gen.next().value); // 'yo'
console.log(gen.next().value); // 'ya'
console.log(gen.next().done); // true
function* idMaker() {
let index = 0;
while (true) {
yield index++;
}
}
let gen = idMaker()
console.log(gen.next().value); // '0'
console.log(gen.next().value); // '1'
console.log(gen.next().value); // '2'
// ...
With ES2015 class
class SimpleClass {
constructor(data) {
this.data = data;
}
[Symbol.iterator]() {
// Use a new index for each iterator. This makes multiple
// iterations over the iterable safe for non-trivial cases,
// such as use of break or nested looping over the same iterable.
let index = 0;
return {
next: () => {
if (index < this.data.length) {
return {value: this.data[index++], done: false}
} else {
return {done: true}
}
}
}
}
}
const simple = new SimpleClass([1,2,3,4,5]);
for (const val of simple) {
console.log(val); // '1' '2' '3' '4' '5'
}
Is a generator object an iterator or an iterable?
A generator object is both iterator and iterable:
let aGeneratorObject = function* () {
yield 1;
yield 2;
yield 3;
}();
console.log(typeof aGeneratorObject.next);
// "function", because it has a next method, so it's an iterator
console.log(typeof aGeneratorObject[Symbol.iterator]);
// "function", because it has an @@iterator method, so it's an iterable
console.log(aGeneratorObject[Symbol.iterator]() === aGeneratorObject);
// true, because its @@iterator method returns itself (an iterator), so it's an well-formed iterable
console.log([...aGeneratorObject]);
// [1, 2, 3]
console.log(Symbol.iterator in aGeneratorObject)
// true, because @@iterator method is a property of aGeneratorObject
Specifications
Specification |
---|
ECMAScript (ECMA-262) The definition of 'Iteration' in that specification. |
See also
- To learn more about ES2015 generators, see:
thefunction*
documentation
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论