Can any one explain this strange behavior about Array sort?

Nit*_*Kio 3 javascript arrays sorting

I have a array like this

a = [0, "-", "-", "-", "-", "-", -0.2, -0.05, 0.25, 0.47, 0.875].

notice that there are some '-' in this array and only this string appears and the left are numbers.

now I apply sort on this array, just like

a = [0, "-", "-", "-", "-", "-", -0.2, -0.05, 0.25, 0.47, 0.875];
console.log(a.sort((a, b) => (+a || -Infinity) - (+b || -Infinity)));
Run Code Online (Sandbox Code Playgroud)

or

a = [0, "-", "-", "-", "-", "-", -0.2, -0.05, 0.25, 0.47, 0.875];
console.log(a.sort((a, b) => (+b || -Infinity) - (+a || -Infinity)));
Run Code Online (Sandbox Code Playgroud)

The results I tried are like this

在此处输入图片说明

so the question is. why desc order works fine but asc order don't?

And*_*erd 5

数组[0, "-"]["-", 0],虽然不同,但都可以根据您定义的排序规则正确地“排序”。

了解javascript sort方法不是稳定的排序。如果要排序的列表中有多个等效项,则这些等效项将分组在一起。但是,在每个组中的顺序都是不确定的。

您正在使用的比较函数将0“-” 定义为等效。

+0是假的,因此+0 || -Infinity将返回-Infinity

+"-"解析为NaN,这也是错误的,因此+"-" || -Infinity将返回-Infinity

当您对降序进行降序排序时,0恰好发生在一个事实上,这-只是实现细节。在其他JavaScript引擎上尝试使用它,或者在下一次Chrome更新后再尝试使用,您可能会得到不同的结果,尽管如此,它仍然是正确的。


如果要将0视为数字(得到的排序结果['-', -0.2, -0.05, 0, 0.25, 0.48, 0.875]),则可以使用以下方法:

a.sort(
    (l,r ) => 
        (typeof(l) === 'number' ? l : -Infinity) -
        (typeof(r) === 'number' ? r : -Infinity)
);

Run Code Online (Sandbox Code Playgroud)

  • 从ES10(一个月前完成)开始,需要Array#sort稳定。当然,要使它可靠将需要一些时间,尤其是在浏览器中。 (3认同)