例如([‘a’,‘b’‘c’,‘d’],2)输出为[[‘a’,b],[c,d]]应该怎么写呢
使用循环呗。
比如以2进行分割
2个循环搞定
for(int i=0;i<2;++i)
{
//存放第一个数组
}
for(int i=2;i<list.size();++i)
{
//存放第二个数组
}
// 定义一个新数组,将2个数组加入进去就可以
arr.reduce((res, item, index) => {
if(index % 2){
res[res.length - 1].push(item)
}else{
res.push([item])
}
return res
}, [])
或者
let i = 0, res = []
while(i < arr.length){
res.push(arr.slice(i, i += 2))
}
console.log(res)