参考文档 https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
用法:
对数组元素进行排序, (直接做用于原数组)
arr.sort(compareFunction)
备注:
a. sort 默认是将比较的双方转成字符串,然后比较ASSIC,
b. 这个在遇到数值类型的数组的时候是明显不行的, 这时候就需要自定义比较函数了,
比较函数 返回true 则排在前面
eg:
var num_array = [1,2,3,4,'5',6,'7',6]; num_array.sort(); console.log(num_array); // [14, 13, "7", 6, 6, "5", 2, 1] num_array.sort(function (x,y) { if (typeof x === 'string') { console.log(x); x = parseInt(x); } if (typeof y === 'string') { y = parseInt(y); } return y-x; }); console.log(num_array); // [14, 13, "7", 6, 6, "5", 2, 1]