javascript中多维数组的迭代器

时间:2016-04-08 07:02:44

标签: javascript ecmascript-6

我正在寻找多维数组的迭代器,我可以轻松地遍历数组。 例如:

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

1 个答案:

答案 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;
&#13;
&#13;