簡體   English   中英

在Javascript中一次按一組4個元素循環遍歷數組?

[英]Loop through an array by set of 4 elements at a time in Javascript?

我有一個很長的數字數組列表,我想一次遍歷數組 4 個元素

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

我想遍歷它們,這樣我就可以使用1-4 , 5-8 , 9-12那樣

使用 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)); }

使用 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) })

注意: Math.ceil用於防止數組長度不能被 4 整除時出現任何錯誤

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM