var sor = ['11', '0', '22', '33'];
for(var i = 0 ; i <=10;i++){
sor.push('11222111111113332323231111'+i);
}
function sortnum(num1,num2){
return num2-num1;
}
sor.sort(sortnum);
$.each(sor,function(index,val){
$('div').append(val+'<br/>');
});
Firefox的结果如下:
122111111111333232323111110
12211111111133323232311113
12211111111133323232311119
12211111111133323232311118
12211111111133323232311110
12211111111133323232311111
12211111111133323232311112
12211111111133323232311117
12211111111133323232311114
12211111111133323232311115
12211111111133323232311116
33
22
11
0
但我期望的是:
122111111111333232323111110
12211111111133323232311119
12211111111133323232311118
12211111111133323232311117
12211111111133323232311116
12211111111133323232311115
12211111111133323232311114
12211111111133323232311113
12211111111133323232311112
12211111111133323232311111
12211111111133323232311110
33
22
11
0
通过减去参数,它们将隐式转换为数字。但是,像这样的数字122111111111333232323111110
刚刚超出范围,Javascript可以(本机地)可以处理的最大整数是9007199254740992
(请参阅this)。
这将导致计算失败。
如果仍要比较这些字符串化的数字,则需要使用自定义比较来比较字符串,而不是依赖于内置数学。它可能看起来像这样:
function compare(a, b) {
if(a.length !== b.length) {
return b.length - a.length;
}
for(var i = 0; i < a.length; i++) {
if(a[i] !== b[i]) {
return b[i] - a[i];
}
}
return 0;
}
看看这个小提琴。但是,这仅适用于正整数。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句