給出一個數組,按長度要求分割成多維數組數組
chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6], 3) should return [[0, 1, 2], [3, 4, 5], [6]] chunkArrayInGroups(["a", "b", "c", "d"], 2) should return [["a", "b"], ["c", "d"]]
1.arr.splice()截取數組
2.當數組元素截取完時,中止截取,返回新數組prototype
function chunkArrayInGroup(arr,size) { var newArr = []; while(arr.length>0) { newArr.push(arr.splice(0,size)); } return newArr; } chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6], 3);
1.arr.slice()截取數組
2.當數組元素截取完時,中止截取,返回新數組code
function chunkArrayInGroup(arr,size) { var newArr = [], i=0; while(i<arr.length) { newArr.push(arr.slice(i,i+size)); i += size; } } chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6], 3);
function chunkArrayInGroups(arr, size) { // Break it up. var arr2 = []; for (var i = 0; i < arr.length; i+=size) { arr2.push(arr.slice(i , i+size)); } return arr2; } chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6], 3);
1.for循環,暫存子數組
2.到達指定長度,存入新數組
3.若有剩餘元素,存入新數組對象
function chunkArrayInGroups(arr, size) { var temp = []; var result = []; for (var a = 0; a < arr.length; a++) { if (a % size !== size - 1) temp.push(arr[a]); else { temp.push(arr[a]); result.push(temp); temp = []; } } if (temp.length !== 0) result.push(temp); return result; } chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6,7], 3);
Array.prototype.push()
Array.prototype.slice()
Array.prototype.splice()
有其餘好的方法或思路的道友,不妨在沙發區神交一番。it