在jQuery中使用整数字符串类型排序数组 [英] sort array with integer strings type in jQuery
本文介绍了在jQuery中使用整数字符串类型排序数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个string类型的整数数组。
I have a array of integers of type string.
var a = ['200','1','40','0','3'];
输出
output
>>> var a = ['200','1','40','0','3'];
console.log(a.sort());
["0", "1", "200", "3", "40"]
我还有一个混合型数组。例如。
I'll also have a mixed type array. e.g.
var c = ['200','1','40','apple','orange'];
输出
output
>>> var c = ['200','1','40','apple','orange']; console.log(c.sort());
["1", "200", "40", "apple", "orange"]
============================================== ====
字符串类型的整数未分类。
==================================================
The integers of string type gets unsorted.
推荐答案
正如其他人所说,你可以编写自己的比较函数:
As others said, you can write your own comparison function:
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"]
这篇关于在jQuery中使用整数字符串类型排序数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文