Array排序
- sort 默认是升序排列(会改变原数组)
var arr = [0, 1, 15, 132, 5, 7, 55, 521];
console.log(arr.sort()); // [0, 1, 132, 15, 5, 521, 55, 7]
//sort()方法的排序默认是对每个元素调用toString()方法然后比较字符大小然后进行排序
//让sort函数按照数值大小排序
var arr = [0, 1, 15, 132, 5, 7, 55, 521];
arr.sort(function(a, b){ return a - b;}); // 升序
console.log(arr) // [0, 1, 5, 7, 15, 55, 132, 521]
arr.sort(function(a, b){ return b - a;}); // 降序
console.log(arr) // [521, 132, 55, 15, 7, 5, 1, 0]
- reverse 倒序
var arr = [0, 1, 15, 132, 5, 7, 55, 521];
console.log(arr.reverse()); // [521, 55, 7, 5, 132, 15, 1, 0]