将数组拆分为给定大小的块 [英] Splitting an array up into chunks of a given size
本文介绍了将数组拆分为给定大小的块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我编写了一个带有两个参数的函数:(1)数组,(2)块的大小.
I have written a function which takes two parameters: (1) an Array, (2) size of the chunk.
function chunkArrayInGroups(arr, size) {
var myArray = [];
for(var i = 0; i < arr.length; i += size) {
myArray.push(arr.slice(i,size));
}
return myArray;
}
我想将此数组拆分为给定大小的块.
I want to split this array up into chunks of the given size.
chunkArrayInGroups(["a", "b", "c", "d"], 2)
应返回: [["a","b"],["c","d"]]
.
我回来了: [["a","b"],[]]
推荐答案
您误解了 切片
参数表示.第二个是索引,直到要获得子数组为止(不包括在内).这不是长度.
You misunderstood what the slice
parameters mean. The second one is the index until which (not included) you want to get the subarray. It's not a length.
array.slice(from, to); // not array.slice(from, length)
function chunkArrayInGroups(arr, size) {
var myArray = [];
for(var i = 0; i < arr.length; i += size) {
myArray.push(arr.slice(i, i+size));
}
return myArray;
}
console.log(chunkArrayInGroups(["a", "b", "c", "d"], 2));
这篇关于将数组拆分为给定大小的块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文