似乎无法确定问题(将数组分成块)
Can't seem to identify the issue (splitting an array in chunks)
所以这个函数应该将数组分成第二个参数大小的块,例如[1, 2, 3, 4] 与第二个参数 2 将 return [[1, 2], [3, 4]],如果数字是 3,它将 return [[1, 2、3]、[4]]等。我的函数似乎以类似的方式运行,但它只有 return 第一个块,后续块只是空数组。我在每次迭代后将索引增加第二个参数,所以我不确定为什么它不起作用。有人可以解释一下这里到底发生了什么以及逻辑中的错误在哪里吗?
let arr = [1, 2, 3, 4, 5, 6]
function test(arr, num) {
let idx = 0;
let newArr = []
while (idx < arr.length) {
newArr.push(arr.slice(idx, num))
idx = idx + num
}
return newArr
}
console.log(test(arr, 2))
您需要一个索引作为 Array#slice
的第二个参数,而不是切片的长度。
比如取第二个数组,index = 2
,第二个参数必须是4
,切片结束的索引
chunks
values 1 2 3 4 5 6
indices 0 1 2 3 4 5
slice 0 2 1 2
2 4 3 4
4 6 5 6
function test(arr, num) {
let idx = 0;
let newArr = [];
while (idx < arr.length) {
newArr.push(arr.slice(idx, idx += num));
}
return newArr;
}
let arr = [1, 2, 3, 4, 5, 6];
console.log(test(arr, 2));
所以这个函数应该将数组分成第二个参数大小的块,例如[1, 2, 3, 4] 与第二个参数 2 将 return [[1, 2], [3, 4]],如果数字是 3,它将 return [[1, 2、3]、[4]]等。我的函数似乎以类似的方式运行,但它只有 return 第一个块,后续块只是空数组。我在每次迭代后将索引增加第二个参数,所以我不确定为什么它不起作用。有人可以解释一下这里到底发生了什么以及逻辑中的错误在哪里吗?
let arr = [1, 2, 3, 4, 5, 6]
function test(arr, num) {
let idx = 0;
let newArr = []
while (idx < arr.length) {
newArr.push(arr.slice(idx, num))
idx = idx + num
}
return newArr
}
console.log(test(arr, 2))
您需要一个索引作为 Array#slice
的第二个参数,而不是切片的长度。
比如取第二个数组,index = 2
,第二个参数必须是4
,切片结束的索引
chunks
values 1 2 3 4 5 6
indices 0 1 2 3 4 5
slice 0 2 1 2
2 4 3 4
4 6 5 6
function test(arr, num) {
let idx = 0;
let newArr = [];
while (idx < arr.length) {
newArr.push(arr.slice(idx, idx += num));
}
return newArr;
}
let arr = [1, 2, 3, 4, 5, 6];
console.log(test(arr, 2));