简体   繁体   English

在javascript中按字典顺序对数组进行排序

[英]sort array lexicographically in javascript

Why does this code为什么这段代码

["Q", "fP", "AQ", "L"].sort((a,b) => a.localeCompare(b))

give this result:给出这个结果:

["AQ", "fP", "L", "Q"]

I thought it would give me this (and that's what I need):我认为它会给我这个(这就是我需要的):

["AQ", "L", "Q", "fP"]

All uppercase letters come before lower case letters chortle.ccsu.edu/java5/Notes/chap92/ch92_2.html所有大写字母都在小写字母之前chortle.ccsu.edu/java5/Notes/chap92/ch92_2.html

Don't use localeCompare() , just use sort() directly不要使用localeCompare() ,直接使用sort()

 let myArray = ["Q", "fP", "AQ", "L"]; myArray.sort(); console.log(myArray);

Interestingly enough, the following works in NodeJS, but not in Browser JavaScript.有趣的是,以下内容适用于 NodeJS,但不适用于浏览器 JavaScript。 This is because the ECMAScript standard doesn't dictate which sorting algorithm to use, so it's up the each browser and/or NodeJS to dictate这是因为 ECMAScript 标准没有规定使用哪种排序算法,所以由每个浏览器和/或 NodeJS 来规定

let myArray = ["Q", "fP", "AQ", "L"];
myArray.sort((a, b) => a > b);
console.log(myArray);

NodeJS Demo NodeJS 演示

https://repl.it/@AnonymousSB/SO53688028 https://repl.it/@AnonymousSB/SO53688028

Documentation文档

http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.11 http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.11

Try this:尝试这个:

 let myArray = ["Q", "fP", "AQ", "L"]; myArray.sort((a, b) => a > b ? 1 : -1); console.log(myArray);

Don't use localeCompare() , just use sort() directly.不要使用localeCompare() ,直接使用sort() As below:如下:

["Q", "fP", "AQ", "L"].sort();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM