首页 > 编程技术 > js

JavaScript数值数组排序示例分享

发布时间:2014-5-31 01:02

但是,我们在使用中就会发现问题,这里的数组排序方法并不是按照我们想像中的数字大小来排序的,而是按照字符串测试结果改变原先的数据。这并不是我们想要的。

那么如何才可以得到我们想要的按照我们思维中的数字大小来排序呢。我们可以自己编写一个函数来实现。


复制代码 代码如下:

var values = [0, 1, 5, 10, 15];
// asc升序函数
function compareAsc(value1, value2) {
    if (value1 > value2) {
        return 1;
    } else if (value1 < value2) {
        return -1;
    } else {
        return 0;
    }
}
// desc降序函数
function compareDesc(value1, value2) {
    if (value1 > value2) {
        return -1;
    } else if (value1 < value2) {
        return 1;
    } else {
        return 0;
    }
}
values.sort(compareAsc);
console.log(values);  // [0, 1, 5, 10, 15]
values.sort(compareDesc);
console.log(values);  // [15, 10, 5, 1, 0]

标签:[!--infotagslink--]

您可能感兴趣的文章: