循环内部的拼接返回错误的值JAVASCRIPT



我想把数组的内容分成4,为此,我首先需要知道每个划分的数组集的内容,我使用Math.ceil。

results = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']; #lenght is 8
let half = Math.ceil(results.length / 4) # half is 2
let whole = [] #i want to insert the spliced value into this array
let j = 0;
let x
for (i = 0; i < 4; i++) {
console.log("j:" + j)
console.log("half: " + half)
x = results.splice(j, half)
console.log(x)
j = j + half;
}

这是我的错误输出:

j:0
half: 2
[ 'a', 'b' ] #this is correct
j:2
half: 2
[ 'e', 'f' ] #this is wrong, it should be ['c','d']
j:4
half: 2
[] #this is wrong, should be ['e','d']
j:6
half: 2
[]#also wrong, should be ['f','g',]

当我在for循环之外测试这个时,它工作得很好,使用索引0,2-2,2-4,2-6,2。可能是什么错误?

拼接方法更改数组的内容(通过移除、替换或添加(。您应该使用末端达到i * 2 + half的切片

results = ["a", "b", "c", "d", "e", "f", "g", "h"]; // #lenght is 8
let half = Math.ceil(results.length / 4); // # half is 2
let whole = []; //#i want to insert the spliced value into this array
let j = 0;
let x;
for (i = 0; i < 4; i++) {
// change the end so that it will take next 2 element pos dynamically
const end = i * 2 + half;
x = results.slice(j, end);
j = j + half;
whole.push(x);
}
console.log(whole);

最新更新