FreeCodeCamp:Chunky Monkey
要求:
猴子吃香蕉可是掰成好几段来吃哦!
把一个数组arr按照指定的数组大小size分割成若干个数组块。
例如:chunk([1,2,3,4],2)=[[1,2],[3,4]];
chunk([1,2,3,4,5],2)=[[1,2],[3,4],[5]];
结果:
chunk(["a", "b", "c", "d"], 2) 应该返回 [["a", "b"], ["c", "d"]].
chunk([0, 1, 2, 3, 4, 5], 3) 应该返回 [[0, 1, 2], [3, 4, 5]].
chunk([0, 1, 2, 3, 4, 5], 2) 应该返回 [[0, 1], [2, 3], [4, 5]].
chunk([0, 1, 2, 3, 4, 5], 4) 应该返回 [[0, 1, 2, 3], [4, 5]].
chunk([0, 1, 2, 3, 4, 5, 6], 3) 应该返回 [[0, 1, 2], [3, 4, 5], [6]].
chunk([0, 1, 2, 3, 4, 5, 6, 7, 8], 4) 应该返回 [[0, 1, 2, 3], [4, 5, 6, 7], [8]].
代码:
方法1:
1 function chunk(arr, size) { 2 // Break it up 3 var temp = []; 4 var result = []; 5 6 for (var a = 0; a < arr.length; a++) { 7 if (a % size !== size - 1) 8 temp.push(arr[a]); 9 else { 10 temp.push(arr[a]); 11 result.push(temp); 12 temp = []; 13 } 14 } 15 16 if (temp.length !== 0) 17 result.push(temp); 18 return result; 19 }
方法二:
1 function chunk(arr, size) { 2 // Break it up 3 // It's already broken :( 4 arr = arr.slice(); 5 var arr2 = []; 6 for(var i = 0, len = arr.length; i < len; i+=size) { 7 arr2.push(arr.slice(0, size)); 8 arr = arr.slice(size); 9 } 10 return arr2; 11 }
方法三:
1 function chunk(arr, size) { 2 // Break it up. 3 var newArr = []; 4 var i = 0; 5 6 while (i < arr.length) { 7 newArr.push(arr.slice(i, i+size)); 8 i += size; 9 } 10 return newArr; 11 } 12 chunk(["a", "b", "c", "d"], 2);
方法四:
1 function chunk(arr, size) { 2 // Break it up 3 var newarr=[]; 4 5 for (var i=0;i<arr.length;i+=size){ 6 newarr.push(arr.slice(i,i+size)); 7 } 8 return newarr; 9 } 10 11 chunk(["a", "b", "c", "d"], 2);