我有一个字符串类型的整数数组。
var a = ['200','1','40','0','3'];
输出
>>> var a = ['200','1','40','0','3'];
console.log(a.sort());
["0", "1", "200", "3", "40"]
我还会有一个混合类型数组。例如
var c = ['200','1','40','apple','orange'];
输出
>>> var c = ['200','1','40','apple','orange']; console.log(c.sort());
["1", "200", "40", "apple", "orange"]
============================================= ===
字符串类型的整数未排序。
最佳答案
正如其他人所说,您可以编写自己的比较函数:
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"]
关于javascript - 在 jQuery 中使用整数字符串类型对数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18554921/