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

时间:2019-12-29 01:49:05

标签: javascript arrays loops

我有一个很长的数字数组列表,我想一次通过4个元素遍历该数组

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

我想遍历它们,以便可以像这样使用1-45-89-12

3 个答案:

答案 0 :(得分:5)

使用for循环,我将其增加4。

注意:当Jaromanda X评论同一件事时,我正在研究答案。

query.initialResultsHandler = {
 query, results, error in

DispatchQueue.main.async {
    let startDate = Calendar.current.date(byAdding: .day, value: -3, to: Date())
    results?.enumerateStatistics(from: startDate,
                              to: Date(), with: { (result, false) in
                                self.moveResult = (Int(result.sumQuantity()?.doubleValue(for: HKUnit.kilocalorie()) ?? 0))})
}

答案 1 :(得分:1)

使用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整除的任何错误

答案 2 :(得分:-1)

lodash chunk方法做到了。

_.chunk(['a', 'b', 'c', 'd'], 2);
// => [['a', 'b'], ['c', 'd']]

_.chunk(['a', 'b', 'c', 'd'], 3);
// => [['a', 'b', 'c'], ['d']]