[英]Loop through an array by set of 4 elements at a time in Javascript?
I have an long list of number array and I want to loop through the array by 4 elements at a time我有一个很长的数字数组列表,我想一次遍历数组 4 个元素
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
I want to loop through them so I can work with 1-4
, 5-8
, 9-12
like that我想遍历它们,这样我就可以使用
1-4
, 5-8
, 9-12
那样
Use a for loop where i increases by 4.使用 for 循环,其中 i 增加 4。
Note: I was working on my answer when Jaromanda X commented the same thing.注意:当 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)); }
Using ES6 and array functions:使用 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) })
Notice: Math.ceil
is used to prevent any error if the array length is not divisible by 4注意:
Math.ceil
用于防止数组长度不能被 4 整除时出现任何错误
The lodash chunk
method does that. lodash
chunk
方法就是这样做的。
_.chunk(['a', 'b', 'c', 'd'], 2);
// => [['a', 'b'], ['c', 'd']]
_.chunk(['a', 'b', 'c', 'd'], 3);
// => [['a', 'b', 'c'], ['d']]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.