嗨,大家好我已经在这个问题上坐了几个小时了,虽然我认为我的代码是正确的,但它仍然无效。我需要得到这个答案:
var newArr = [[" a"," b"],[" c"," d"]]
(arr和大小永远是变量)
function separateIt(arr, size) {
var newArr = [];
for(var i = 0; i < arr.length; i += size){
var sliceIt = arr.slice(arr[i],[arr[i]+size]);
newArr.push(sliceIt);
}
return newArr;
}
console.log(separateIt(["a", "b", "c", "d"], 2));
感谢任何帮助,我是初学者:)
答案 0 :(得分:1)
您可以使用索引而不是数组的值
var sliceIt = arr.slice(i, i + size);
// ^ ^^^^^^^^
function separateIt(arr, size) {
var newArr = [];
for (var i = 0; i < arr.length; i += size) {
var sliceIt = arr.slice(i, i + size);
newArr.push(sliceIt);
}
return newArr;
}
console.log(separateIt(["a", "b", "c", "d"], 2));
答案 1 :(得分:0)
我建议的最简单方法如下:
function separateIt(arr, size) {
// creating a new Array to return
// to the calling context:
let res = [];
while (arr.length) {
// appending a new Array created from the
// first element to the size-th element,
// modifying the original array ('arr')
// by removing those elements:
res.push(arr.splice(0, size));
}
// returning the new Array:
return res;
}
console.log(separateIt(["a", "b", "c", "d"], 2));
&#13;