sort是数组方法,用于数组排序,会改变原数组
1.当未传参数时,是按照字符编码的顺序进行排序
let arr = [1, 4, 9, 4, 0, 6, 0, 7];
console.log(arr.sort()) // [0, 0, 1, 4, 4, 6, 7, 9]
let arr1 = ['a', '1', 'c', 'q', '9', '0']
console.log(arr1.sort()) // ['0', '1', '9', 'a', 'c', 'q']
let arr2 = ['a', '1', 'V', 'q', 'A', '0']
console.log(arr2.sort()) // ['0', '1', 'A', 'V', 'a', 'q']
2.传参数时,a - b 为升序, b - a 是降序
let arr3 = [1, 4, 9, 4, 0, 6, 0, 7];
arr3.sort((a, b) => a - b)
/*
写法1:
数组.sort(function (a, b) {
return a - b
})
写法2:
数组.sort((a, b) => {
return a - b
})
*/
console.log(arr3) // [0, 0, 1, 4, 4, 6, 7, 9]
// 降序
let arr3 = [1, 4, 9, 4, 0, 6, 0, 7];
arr3.sort((a, b) => b - a)
console.log(arr3) // [9, 7, 6, 4, 4, 1, 0, 0]
|