Javascript sort() 方法

2019-01-18  本文已影响17人  觉子先生

突然需要对数组进行排序,然后才又回过头来温习这东西,真的超久没用到了…(⊙_⊙;)…
按照习惯通过看例子进行了解吧。

例1:

var arr = []
arr[0] = "xiaodong"
arr[1] = "zhangyu"
arr[2] = "huyong"
arr[3] = "minglin"
arr[4] = "dasheng"
arr[5] = "anan"

console.log(arr.sort()) //排序后:["anan", "dasheng", "huyong", "minglin", "xiaodong", "zhangyu"]

例2:

var arr = []
arr[0] = "10"
arr[1] = "5"
arr[2] = "40"
arr[3] = "25"
arr[4] = "1000"
arr[5] = "1"

console.log(arr) //排序前:["10", "5", "40", "25", "1000", "1"]
console.log(arr.sort()) //排序后:["1", "10", "1000", "25", "40", "5"],明显可以看出这里并没有按照数字大小排列,而是以字符串的形式按照首字母依次排序的

例3:

function sortIncrease(a,b){
  return a - b
}
function sortDecrease (a,b){
  return b - a
}

var arr = []
arr[0] = "10"
arr[1] = "5"
arr[2] = "40"
arr[3] = "25"
arr[4] = "1000"
arr[5] = "1"

console.log(arr.sort(sortIncrease)) //递增排序后:["1", "5", "10", "25", "40", "1000"]
console.log(arr.sort(sortDecrease)) //递减排序后:["1000", "40", "25", "10", "5", "1"]

完。

上一篇下一篇

猜你喜欢

热点阅读