简体   繁体   English

在Javascript中一次按一组4个元素循环遍历数组?

[英]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.

相关问题 使用JavaScript遍历嵌套数组元素 - Loop Through Nested Array Elements With JavaScript 显示元素时Javascript遍历数组 - Javascript Loop through Array while displaying the elements javascript 循环遍历元素的动态数组,获取值然后使用值作为间隔来设置计时器倒计时 - javascript loop through dynamic array of elements, get values then use values as interval to set timer countdown 需要遍历数组并将每个值一次设置为 Javascript 中的一个类 - Need to loop through an array and set each value one at a time to a class in Javascript javascript:遍历对象数组并将元素推入一个数组 - javascript: loop through object array and pushing elements into one array 在JavaScript中循环使用一组元素的最佳方法是什么? - What's the best way to loop through a set of elements in JavaScript? 遍历元素集并从不同数组中添加适当的值 - Loop through set of elements and add proper value from different array Javascript:通过函数循环遍历数组中的两个数组和求和元素 - Javascript: Loop Through Two Arrays and Sum Elements in Array Via Function JQuery / Javascript选择器使用toggle()或add / removeClass()循环遍历元素数组 - JQuery / Javascript selector loop through array of elements with toggle() or add/removeClass() 遍历一个javascript数组 - loop through a javascript array
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM