在 Safari 控制台中:
var x = ["20", "21"]; x.sort(function(a,b){return b > a}); x
> ["20", "21"]
Chrome:
var x = ["20", "21"]; x.sort(function(a,b){return b > a}); x
> ["21", "20"]
不过,这在 Safari 中按预期工作(与 Chrome 匹配):
"20" > "21"
false
挠我的头。
最佳答案
Array#sort
需要对您要排序的类型进行回调。
基本上您需要使用数字进行排序,因为字符串对字符串进行排序,而不是对数字进行排序。第一个按字符串排序,第二个按数值排序。
var x = ["20", "21", "2", "100", "10", "1", "3", "30"];
x.sort();
console.log(x);
x.sort(function (a, b) {
return a - b; // implicit casting to Number
});
console.log(x);
关于javascript - Safari 浏览器 Javascript 数组似乎对字符串排序不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38415636/