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

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});

你可能感兴趣的:(2018-11-12 js数组排序默认使用字母顺序,想要对整数数组排序请加排序函数)