|
Posted on 2007-10-01 09:56 诗特林 阅读(1908) 评论(0) 编辑 收藏 所属分类: JavaScript
JavaScript中的数字排序方法
1.普通排序
var a = [0,null,10,11,null,20,100,null,-10,-1,111,2, null, 5];
a.sort();
console.log(a);
输出结果:
[-1, -10, 0, 10, 100, 11, 111, 2, 20, 5, null, null, null, null]
2.一般排序
function numberAsc(a, b) { return a - b;}
var a = [0,null,10,11,null,20,100,null,-10,-1,111,2, null, 5];
a.sort(numberAsc);
console.log("asc: ", a);
输出结果:
asc: [-10, -1, null, null, null, 0, null, 2, 5, 10, 11, 20, 100, 111]
3.高级排序
function numberAsc(a, b) { return a - b;}
function numberDesc(a, b) { return b - a;}
var a = [0,null,10,11,null,20,100,null,-10,-1,111,2, null, 5];
a.sort(numberAsc);console.log("asc: ", a);
a.sort(numberDesc)console.log("desc: ", a);
a.sort(numberAsc);console.log("asc: ", a);
a.sort(numberDesc)console.log("desc: ", a);
输出结果
asc: [-10, -1, null, null, null, 0, null, 2, 5, 10, 11, 20, 100, 111]
desc: [111, 100, 20, 11, 10, 5, 2, 0, null, null, null, null, -1, -10]
asc: [-10, -1, null, null, null, null, 0, 2, 5, 10, 11, 20, 100, 111]
desc: [111, 100, 20, 11, 10, 5, 2, null, null, null, 0, null, -1, -10]
4.终极排序
var ALMOST_ZERO = -0.00000001;
function numberAsc(a, b) {
var left = a != null ? a : ALMOST_ZERO;
var right = b != null ? b : ALMOST_ZERO;
return left - right;
}
输出结果
asc: [-10, -1, null, null, null, null, 0, 2, 5, 10, 11, 20, 100, 111]
desc: [111, 100, 20, 11, 10, 5, 2, 0, null, null, null, null, -1, -10]
asc: [-10, -1, null, null, null, null, 0, 2, 5, 10, 11, 20, 100, 111]
desc: [111, 100, 20, 11, 10, 5, 2, 0, null, null, null, null, -1, -10]
|