为什么javascript的排序功能不好用? [英] Why doesn't the sort function of javascript work well?
本文介绍了为什么javascript的排序功能不好用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这个简单的javascript
This simple javascript
var x = new Array();
x[0] = 2.73;
x[1] = 11.17;
x[2] = 3.12
x.sort();
for(var i in x)
alert(x[i]);
产生结果:11.17, 2.73, 3.12
而不是 2.73, 3.12, 11.17
.
produces the results:
11.17, 2.73, 3.12
instead of 2.73, 3.12, 11.17
.
这是为什么,我该如何解决?
Why is that and how can I fix it?
提前致谢!
推荐答案
是按字母顺序排序的,试试传递自己的排序函数:
It's sorting alphabetically, try passing your own sorting function:
var x = new Array();
x[0] = 2.73;
x[1] = 11.17;
x[2] = 3.12;
numberSort = function (a,b) {
return a - b;
};
x.sort(numberSort);
for(var i in x) {
alert(x[i]);
}
这篇关于为什么javascript的排序功能不好用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文