我试图根据动态提供的大小创建新数组
为什么会这样?
function chunkArrayInGroups(arr, size) {
// Break it up.
var updatedarr = [];
for (var i = 0; i < arr.length; i++) {
for (var j = 0; j < size; j++) {
updatedarr[i][j] = arr[i];
}
}
return updatedarr;
}
chunkArrayInGroups(["a", "b", "c", "d"], 2);
&#13;
答案 0 :(得分:0)
您可以通过
来分块function chunkArrayInGroups(arr, size) {
var updatedarr=[];
for(var i =0;i<arr.length ;i+=size) {
updatedarr.push([]);
//pushing the array which gonna contain the chunk.
for(var j=i;j<i+size;j++) { // run loop from i to i+size ex: 0->2 when i = 0.
//picking the last chunk array and pushing the values
updatedarr[updatedarr.length - 1].push(arr[j]);
}
}
return updatedarr;
}
chunkArrayInGroups(["a", "b", "c", "d","e","f","g"], 2);
输出将是,
[["a","b"],["c","d"],["e","f"],["g"]]
根据你评论中的新要求,你必须在未定义的时候使用break。
function chunkArrayInGroups(arr, size) {
var updatedarr=[];
for(var i =0;i<arr.length ;i+=size) {
updatedarr.push([]);
for(var j=i;j<i+size;j++) {
if(typeof arr[j] == "undefined") break;
updatedarr[updatedarr.length - 1].push(arr[j]);
}
}
return updatedarr;
}
chunkArrayInGroups([0, 1, 2, 3, 4, 5], 4);
输出:
[[0, 1, 2, 3], [4, 5]]