我有一个string类型的整数数组.
var a = ['200','1','40','0','3'];
Run Code Online (Sandbox Code Playgroud)
>>> var a = ['200','1','40','0','3'];
console.log(a.sort());
["0", "1", "200", "3", "40"]
Run Code Online (Sandbox Code Playgroud)
我也有一个混合型数组.例如
var c = ['200','1','40','apple','orange'];
Run Code Online (Sandbox Code Playgroud)
>>> var c = ['200','1','40','apple','orange']; console.log(c.sort());
["1", "200", "40", "apple", "orange"]
Run Code Online (Sandbox Code Playgroud)
==================================================
字符串类型的整数未分类.
Kaz*_*uki 17
正如其他人所说,你可以编写自己的比较函数:
var arr = ["200", "1", "40", "cat", "apple"]
arr.sort(function(a,b) {
if (isNaN(a) || isNaN(b)) {
return a > b ? 1 : -1;
}
return a - b;
});
// ["1", "40", "200", "apple", "cat"]
Run Code Online (Sandbox Code Playgroud)
这应该是你正在寻找的
var c = ['200','1','40','cba','abc'];
c.sort(function(a, b) {
if (isNaN(a) || isNaN(b)) {
if (a > b) return 1;
else return -1;
}
return a - b;
});
// ["1", "40", "200", "abc", "cba"]
Run Code Online (Sandbox Code Playgroud)