我正在寻找多维数组的迭代器,我可以轻松地遍历数组。 例如:
var multipeArrayLike = [[1,[21,22],3,4],[5,6,7,8]]
var iterator = getIterator(multipeArrayLike)
console.log(iterator.next().value) // should return 1
console.log(iterator.next().value) // should return 21
console.log(iterator.next().value) // should return 22
console.log(iterator.next().value) // should return 3
console.log(iterator.next().value) // should return 4
console.log(iterator.next().value) // should return 5
....
console.log(iterator.next().value) // should return 8
答案 0 :(得分:4)
您可以使用类似于此的递归生成器:
'use strict';
function *flat(a) {
if (!Array.isArray(a)) {
yield a;
} else {
for (let x of a)
yield *flat(x);
}
}
var multipeArrayLike = [[1, [21, 22], 3, 4], [5, 6, 7, 8]]
for (let y of flat(multipeArrayLike))
document.write('<pre>'+JSON.stringify(y,0,3));
&#13;