gpt4 book ai didi

javascript - 是否可以使用 for...of 和/或 for...in 循环遍历嵌套数组?

转载 作者:搜寻专家 更新时间:2023-11-01 04:59:18 24 4
gpt4 key购买 nike

假设我有一个由嵌套数组组成的“矩形网格”,如下所示:

let board = [
['a0', 'a1', 'a2', 'a3', 'a4'],
['b0', 'b1', 'b2', 'b3', 'b4'],
['c0', 'c1', 'c2', 'c3', 'c4'],
['d0', 'd1', 'd2', 'd3', 'd4'],
];

我试图遍历其列,因此结果将类似于'a0'、'b0'、'c0'、'd0'、'a1'...等等

当然我可以使用旧的 for 循环来做到这一点:

const iterateAcrossColumnsES5 = () => {
for (let i = 0; i < board[0].length; i++) {
for (let j = 0; j < board.length; j++) {
console.log(board[j][i]);
}
}
}

但我喜欢尝试让它更像 ES6 一样简洁和可读。我正在尝试使用 for.. of 和/或 for.. in 循环,但我只得到了:

const iterateAcrossColumnsES6 = () => {
for (let [i, item] of Object.entries(board)) {
for(let row of board) {
console.log(row[i])
}
}
}

但它既不简洁也不可读,而且只有在 board 是“正方形”(父数组length 与其 child 的长度相同),否则我得到的迭代次数太多或不够。

有可能吗?我还没有尝试使用 map()forEach(),我没问题。与他们一起,但我很好奇我是否只能使用 for..offor..in

最佳答案

在 js 中没有内置的东西,但是有两个小的辅助函数,你可以用一种非常优雅的方式编写循环:

function *chain(its) {
for (let it of its)
yield *it
}

function zip(arrays) {
return arrays[0].map((e, i) => arrays.map(a => a[i]))
}

//

let board = [
['a0', 'a1', 'a2', 'a3', 'a4'],
['b0', 'b1', 'b2', 'b3', 'b4'],
['c0', 'c1', 'c2', 'c3', 'c4'],
['d0', 'd1', 'd2', 'd3', 'd4'],
]


console.log([...chain(board)].join(' '))


console.log([...chain(zip(board))].join(' '))

chain 连接多个可迭代对象,以便您可以将它们作为一个事物进行迭代,zip 获取一个数组数组并将其转置。

关于javascript - 是否可以使用 for...of 和/或 for...in 循环遍历嵌套数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53227119/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com