sort():对数组的元素进行排序,默认从小到大排序
(1)直接使用sort()
let array = ['❆LO❆','AND','❆VE❆','❆LOVE❆']
let array2 = array.sort()
console.log(array,array2) //['AND', '❆LOVE❆', '❆LO❆', '❆VE❆'] ['AND', '❆LOVE❆', '❆LO❆', '❆VE❆']
//原array数组:['❆LO❆','AND','❆VE❆','❆LOVE❆']
(2)自定义升序
var array = [ 7, 2, 9, 4, 5, 6 ];
let array2 = array.sort((a,b)=>a-b)
console.log(array,array2) //[2, 4, 5, 6, 7, 9] [2, 4, 5, 6, 7, 9]
//原array:[ 7, 2, 9, 4, 5, 6 ]
(3)自定义降序
var array = [ 7, 2, 9, 4, 5, 6 ];
let array2 = array.sort((a,b)=>b-a)
console.log(array,array2) //[9, 7, 6, 5, 4, 2] [9, 7, 6, 5, 4, 2]
//原array:[ 7, 2, 9, 4, 5, 6 ]