我有一个很长的数字数组列表,我想一次循环4个元素的数组
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]我想遍历它们,这样我就可以像这样使用1-4、5-8、9-12
发布于 2019-12-29 09:53:45
使用for循环,其中i增加4。
注意:当Jaromanda X评论同样的事情时,我正在做我的答案。
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
for (var i = 0; i < arr.length; i += 4) {
console.log("Working with: " + arr.slice(i, i + 4));
}
发布于 2019-12-29 10:11:12
使用ES6和数组函数:
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
[...Array(Math.ceil(arr.length / 4)).keys()].forEach(i => {
const [a, b, c, d] = arr.slice(i * 4, (i+1) * 4)
// a, b, c and d are the four elements of this iteration
console.log(`iteration n°${i}`, a, b, c, d)
})
注意:如果数组长度不能被4整除,则使用Math.ceil来防止任何错误
发布于 2019-12-29 09:56:03
lodash chunk方法可以做到这一点。
_.chunk(['a', 'b', 'c', 'd'], 2);
// => [['a', 'b'], ['c', 'd']]
_.chunk(['a', 'b', 'c', 'd'], 3);
// => [['a', 'b', 'c'], ['d']]https://stackoverflow.com/questions/59516304
复制相似问题