如果你使用 ES2015 并且你想定义你自己的像二维数组一样迭代的对象,你可以通过以下方式实现迭代器协议:
- 定义一个调用的@@iterator
Symbol.iterator
函数,它返回...
- ...一个具有
next()
返回函数的对象...
- ...一个具有一个或两个属性的对象:一个
value
具有下一个值(如果有的话)的可选值和一个布尔值done
,如果我们完成迭代,则为真。
一维数组迭代器函数如下所示:
// our custom Cubes object which implements the iterable protocol
function Cubes() {
this.cubes = [1, 2, 3, 4];
this.numVals = this.cubes.length;
// assign a function to the property Symbol.iterator
// which is a special property that the spread operator
// and for..of construct both search for
this[Symbol.iterator] = function () { // can't take args
var index = -1; // keep an internal count of our index
var self = this; // access vars/methods in object scope
// the @@iterator method must return an object
// with a "next()" property, which will be called
// implicitly to get the next value
return {
// next() must return an object with a "done"
// (and optionally also a "value") property
next: function() {
index++;
// if there's still some values, return next one
if (index < self.numVals) {
return {
value: self.cubes[index],
done: false
};
}
// else there's no more values left, so we're done
// IF YOU FORGET THIS YOU WILL LOOP FOREVER!
return {done: true}
}
};
};
}
现在,我们可以将我们的Cubes
对象视为可迭代对象:
var cube = new Cubes(); // construct our cube object
// both call Symbol.iterator function implicitly:
console.log([...cube]); // spread operator
for (var value of cube) { // for..of construct
console.log(value);
}
要创建我们自己的2-Dnext()
可迭代对象,我们可以返回另一个可迭代对象,而不是在函数中返回值:
function Cubes() {
this.cubes = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
];
this.numRows = this.cubes.length;
this.numCols = this.cubes[0].length; // assumes all rows have same length
this[Symbol.iterator] = function () {
var row = -1;
var self = this;
// create a closure that returns an iterator
// on the captured row index
function createColIterator(currentRow) {
var col = -1;
var colIterator = {}
// column iterator implements iterable protocol
colIterator[Symbol.iterator] = function() {
return {next: function() {
col++;
if (col < self.numCols) {
// return raw value
return {
value: self.cubes[currentRow][col],
done: false
};
}
return {done: true};
}};
}
return colIterator;
}
return {next: function() {
row++;
if (row < self.numRows) {
// instead of a value, return another iterator
return {
value: createColIterator(row),
done: false
};
}
return {done: true}
}};
};
}
现在,我们可以使用嵌套迭代:
var cube = new Cubes();
// spread operator returns list of iterators,
// each of which can be spread to get values
var rows = [...cube];
console.log([...rows[0]]);
console.log([...rows[1]]);
console.log([...rows[2]]);
// use map to apply spread operator to each iterable
console.log([...cube].map(function(iterator) {
return [...iterator];
}));
for (var row of cube) {
for (var value of row) {
console.log(value);
}
}
请注意,我们的自定义迭代不会在所有情况下都表现得像二维数组。例如,我们还没有实现一个map()
函数。这个答案显示了如何实现生成器映射函数(请参阅此处了解迭代器和生成器之间的区别;此外,生成器是 ES2016 功能,而不是 ES2015,因此如果您使用 babel 进行编译,则需要更改 babel 预设)。