☒??Chunky Monkey -- Freecodecamp

Q1:方法1逻辑不通呀,不明白??

Q2:方法2中,arr = arr.slice();//没有也正常执行,那么存在的意义是什么??

Write a function that splits an array (first argument) into groups the length of size (second argument) and returns them as a two-dimensional array.
Here are some helpful links:
Array.prototype.push()
Array.prototype.slice()
chunkArrayInGroups(["a", "b", "c", "d"], 2) should return [["a", "b"], ["c", "d"]].
chunkArrayInGroups([0, 1, 2, 3, 4, 5], 3) should return [[0, 1, 2], [3, 4, 5]].
chunkArrayInGroups([0, 1, 2, 3, 4, 5], 2) should return [[0, 1], [2, 3], [4, 5]].
chunkArrayInGroups([0, 1, 2, 3, 4, 5], 4) should return [[0, 1, 2, 3], [4, 5]].
chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6], 3) should return [[0, 1, 2], [3, 4, 5], [6]].
chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 4) should return [[0, 1, 2, 3], [4, 5, 6, 7], [8]].
chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 2) should return [[0, 1], [2, 3], [4, 5], [6, 7], [8]]

Q1:不懂??逻辑不通呀

//方法1:??
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;
}```

//方法2:slice() + push()
function chunkArrayInGroups(arr, size) {
arr = arr.slice();//没有也正常执行,那么存在的意义是什么??
var arr2 = [];
for(var i = 0, len = arr.length; i < len; i+=size) {
arr2.push(arr.slice(0, size));
arr = arr.slice(size);
}
return arr2;
}```

//方法3:while + push
function chunkArrayInGroups(arr, size) {
  // Break it up.
  var newArr = [];
  var i = 0;

  while (i < arr.length) {
    newArr.push(arr.slice(i, i+size));
    i += size;
  }
  return newArr;
}
chunkArrayInGroups(["a", "b", "c", "d"], 2);```


https://github.com/freeCodeCamp/freeCodeCamp/wiki/Algorithm-Chunky-Monkey

你可能感兴趣的:(☒??Chunky Monkey -- Freecodecamp)