Javascript拼接方法中的怪异错误

Fai*_*sha 6 javascript sorting algorithm array-algorithms

我有一个包含“零”的数组,我想将所有“零”移到该数组的最后一个索引。

预期的输出是:

[1,2,3,0,0,0,0]
Run Code Online (Sandbox Code Playgroud)

但是我得到了:

[1,2,0,3,0,0,0]
Run Code Online (Sandbox Code Playgroud)

Joh*_*ohn 9

当您从数组中删除该项目时,所有元素都向下移动一位。前进索引(i ++)时,跳过数组中下移的项,该项恰好是数组中的连续零。

解决方案:向后进行for next循环,它将起作用。


Nin*_*olz 3

由于 splice 会更改数组的长度,因此您可以从数组末尾开始迭代,并将找到的值直接拼接到最后一个索引。

使用这种方法,您只需要一个循环。

var a = [0, 1, 2, 0, 0, 3, 0],
    i = a.length;

while (i--) {
    if (a[i] === 0) {
        a.splice(a.length, 0, ...a.splice(i, 1));
    }
}

console.log(a);
Run Code Online (Sandbox Code Playgroud)

一种无需拼接的更短方法 - 并且从零开始。

var a = [0, 1, 2, 0, 0, 3, 0],
    i, j = 0;

for (i = 0; i < a.length; i++) {
    if (a[i] !== 0) {
        [a[j], a[i]] = [a[i], a[j]]; // swap
        j++;
    }        
}

console.log(a);
Run Code Online (Sandbox Code Playgroud)