2018-11-12 js数组排序默认使用字母顺序,想要对整数数

2018-11-12  本文已影响15人  五大RobertWu伍洋

js数组排序默认使用字母顺序,想要对整数数组排序:

function sortNumber(a,b) {
    return a - b;
}

var numArray = [140000, 104, 99];
numArray.sort(sortNumber);
alert(numArray.join(","));

EDIT: using ES6 arrow functions:

numArray.sort((a, b) => a - b); // For ascending sort
numArray.sort((a, b) => b - a); // For descending sort

w3c教程中默认的js排序和逆序举例

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();        // First sort the elements of fruits 
fruits.reverse();     // Then reverse the order of the elements

按照数值排序

var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a - b});
上一篇下一篇

猜你喜欢

热点阅读