我有一个很长的数字数组列表,我想一次通过4个元素遍历该数组
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
我想遍历它们,以便可以像这样使用1-4
,5-8
,9-12
答案 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']]