las*_*ger 0 javascript v8 node.js
我发现 sort 方法在 Chrome 环境和节点环境中显示不同的行为
const arr = ['l', 'h', 'z', 'b', 's'];
arr.sort((pre, next) => {
return pre < next;
});
console.log(arr);
Run Code Online (Sandbox Code Playgroud)
节点环境的结果是[ 'z', 's', 'l', 'h', 'b' ],它已排序。
chrome 控制台环境的结果是['l', 'h', 'z', 'b', 's'],没有任何改变。
chrome 的结果是我所期望的,我不明白为什么它在节点环境中工作。
chrome 版本是74.0.3729.169 X64
node vsrions 是v10.12.0.
V8 developer here.
As some of the comments are getting at, this is not about Chrome vs. Node (which should behave the same way). It's due to a difference in V8 versions, where Chrome 74 already has the new behavior whereas Node 10 still has the old. Update to Node 11 and you'll see that same behavior there.
In the past, V8 used a combination of QuickSort (for larger arrays) and InsertionSort (for small arrays, up to 10 elements). InsertionSort just so happens to work correctly with the bad comparator function. Use a test array with 11 elements or more, and it will no longer sort correctly in Node 10.
(Versions of V8 since 7.4 now use TimSort for Array.prototype.sort.)
I know that that's not what this question is about, but for the record and/or anyone else reading this in the future: (pre, next) => pre <= next is not a good comparator function! In JavaScript, Array.prototype.sort expects a comparator that returns a number less than zero, equal to zero, or greater than zero, depending on whether the first argument is less than, equal to, or greater than the second. So the proper way to sort strings is something like:
my_string_array.sort((a, b) => {
if (a < b) return -1;
if (a > b) return 1;
return 0;
});
Run Code Online (Sandbox Code Playgroud)
When you use such a comparator, you will always get the right result, in all versions of Chrome and Node.
When you use a comparator that uses a single comparison and hence returns a boolean value, then true silently maps to 1 and false maps to 0, but that means it accidentally returns "equal" for a bunch of pairs that are not, in fact, equal, which can lead to quite surprising sorting results, especially when the engine uses an unstable sorting algorithm under the hood.
| 归档时间: |
|
| 查看次数: |
127 次 |
| 最近记录: |