FreeCodeCampChina / freecodecamp.cn

FCC China open source codebase and curriculum. Learn to code and help nonprofits.

Home Page:https://fcc.asia/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

有没有更好的写法?

seakingxc opened this issue · comments

Challenge Chunky Monkey has an issue.
User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36.
Please describe how to reproduce this issue, and include links to screenshots if possible.

My code:

function chunk(arr, size) {
  // 请把你的代码写在这里
  var newarr=[];
  //每size个元素为一组 可以分为arr.length/size组
  var arrcount = parseInt(arr.length/size);
  //判断是否可以整除
  if(arr.length%size>0){
    arrcount +=1;
  }
  //循环arrcount次组装新数组  第一组坐标是0-size 每临近2组坐标相对增加size
  for(var i = 0;i<arrcount;i++){
    //用slice方法切片
    var x = i*size;
    newarr.push(arr.slice(0+x,size+x));
  }
  
  return newarr;
}

chunk(["a", "b", "c", "d","e"], 2);

@seakingxc https://singsing.io/blog/fcc/basic-chunky-monkey/
可以参考最后的那个方法,用 splice

function chunk(arr, size) {
// 请把你的代码写在这里
var newArr = [];
for(var i = 0;i < arr.length;i += size){
var num = arr.slice(i,i + size);
newArr.push(num);
}
return newArr;
}