编写一个将数组(第一个参数)分成大小(第二个参数)长度的组并将其作为多维数组返回的函数 [英] Write a function that splits an array (first argument) into groups the length of size (second argument) and returns them as a multidimensional array
本文介绍了编写一个将数组(第一个参数)分成大小(第二个参数)长度的组并将其作为多维数组返回的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在解决一个JavaScript问题,要求我执行以下操作:
I am working through a javascript problem that asks me to:
编写一个将数组(第一个参数)分成大小(第二个参数)长度的组并将其作为多维数组返回的函数.
Write a function that splits an array (first argument) into groups the length of size (second argument) and returns them as a multidimensional array.
例如输入
chunk([0, 1, 2, 3, 4, 5], 2)
应返回块数组":[[0,1],[2,3],[4,5]]
should return the 'chunked arrays': [[0, 1], [2, 3], [4, 5]]
对于大多数示例,我都可以使用它,但是当有两个以上的块时,它将切换顺序,我不确定为什么.这是我编写的代码:
I can get it to work for most examples but when there are more than 2 chunks it switches the order and I am not sure why. Here is the code that I have written:
function chunk(arr, size) {
var newArray = [],
i, temp = arr;
for (i = 0;i<= arr.length-size;i+=size){
newArray.push(arr.slice(i,i+size));
temp.splice(i,size);
}
newArray.push(temp);
return newArray;
}
chunk(['a', 'b', 'c', 'd'], 2);
推荐答案
另一个版本:
function chunk(arr, size) {
var result = [];
while (arr.length > size) {
result.push(arr.splice(0, size))
}
if (arr.length)
result.push(arr);
return result;
}
这篇关于编写一个将数组(第一个参数)分成大小(第二个参数)长度的组并将其作为多维数组返回的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文