【发布时间】:2019-01-18 15:51:42
【问题描述】:
我有以下 JavaScript 代码:
const ary = ["Kevin", "brandy", "Andrew"];
const nary = ary.sort();
console.log(nary);
我希望上述代码的输出是["Andrew","brandy", "Kevin"],即根据字典的单词顺序。
但是在控制台中我得到了输出:
["Andrew","Kevin","brandy"]
当我将"brandy" 中的b 切换为大写B,并再次运行代码时,
const ary = ["Kevin", "Brandy", "Andrew"];
const nary = ary.sort();
console.log(nary);
输出如预期:
["Andrew","Brandy","Kevin"]
即根据单词的字典顺序。
即优先排序首字母为大写的单词,再排序首字母为小写的单词。
我的问题是:
为什么在 JavaScript 中会发生这种情况?
如何使用
sort()函数根据字典的单词顺序对字符串数组["Kevin", "brandy", "Andrew"]进行排序?
Input code:
const ary = ["Kevin", "brandy", "Andrew"];
const nary = ary.sort();
console.log(nary);
Console Output:
["Andrew","Kevin","brandy"]
I want the Output as:
["Andrew","brandy", "Kevin"]
【问题讨论】:
-
这个问题已经有几个答案了,这里有一个候选人stackoverflow.com/questions/8996963/…
-
对于您的第 1 点,在控制台中键入
"a" > "B"。或"a".codePointAt(0)&"B".codePointAt(0)
标签: javascript arrays sorting