javascript 在jQuery中使用整数字符串类型对数组进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18554921/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
sort array with integer strings type in jQuery
提问by beebek
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.
==================================================
字符串类型的整数未排序。
回答by Kazuki
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"]
回答by Graham Walters
This should be what you're looking for
这应该是你要找的
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"]
回答by Tap
You need to write your own sort function.
您需要编写自己的排序函数。
a.sort(function(a,b)) {
var intValA = parseInt(a, 10);
var intValB = parseInt(b, 10);
if (!isNaN(parseInt(a, 10))) && !isNaN(parseInt(b, 10)) {
// we have two integers
if (intValA > intValB)
return 1;
else if (intValA < intValB)
return 0;
return 1;
}
if (!isNaN(parseInt(a, 10)) && isNaN(parseInt(b, 10)))
return 1;
if (isNaN(parseInt(a, 10)) && !isNaN(parseInt(b, 10)))
return -1;
// a and b are not integers
if (a > b)
return 1;
if (a < b)
return -1;
return 0;
});
回答by beebek
Thanks all, though I dont know jQuery much, but from you guys examples, I summarized the code as follows which works as per my requirement
谢谢大家,虽然我不太了解 jQuery,但是从你们的例子中,我总结了以下代码,这些代码按我的要求工作
to be used in firebug
用于萤火虫
var data = ['10','2', 'apple', 'c' ,'1', '200', 'a'], temp;
temp = data.sort(function(a,b) {
var an = +a;
var bn = +b;
if (!isNaN(an) && !isNaN(bn)) {
return an - bn;
}
return a<b ? -1 : a>b ? 1 : 0;
}) ;
alert(temp);
回答by ermagana
Most javascript implementations, as far as I know, provide a function you can pass in to provide your own custom sorting.
据我所知,大多数 javascript 实现都提供了一个函数,您可以传入它来提供您自己的自定义排序。