数组排序方法给不一样,我这就讲解一下最简单使用的排序。sort、冒泡排序、reverse倒序
- sort
let arr = [2, 34, 1, 4, 6, 8, 9, 7, 9, 1, 4, 5, 293, 83]
arr.sort((a, b) => {
//b - a:从大到小;a - b:从小到大
return a - b
})
console.log(arr); // [1, 1, 2, 4, 4, 5, 6, 7, 8, 9, 9, 34, 83, 293]
- 冒泡排序
let arr = [2, 34, 1, 4, 6, 8, 9, 7, 9, 1, 4, 5, 293, 83]
for (let index = 0; index < arr.length; index++) {
for (let num = 0; num < arr.length; num++) {
const numValue = arr[num];
// <:从大到小;>:从小到大
if (numValue < arr[num + 1]) {
//调换数组里面值的位置
arr[num] = arr[num + 1]
arr[num + 1] = numValue
}
}
}
console.log(arr); // [293, 83, 34, 9, 9, 8, 7, 6, 5, 4, 4, 2, 1, 1]
- reverse倒序
let arr = [2, 34, 1, 4, 6, 8, 9, 7, 9, 1, 4, 5, 293, 83]
arr.reverse()
console.log(arr); // [83, 293, 5, 4, 1, 9, 7, 9, 8, 6, 4, 1, 34, 2]