突然需要對數(shù)組進(jìn)行排序,然后才又回過頭來溫習(xí)這東西纹冤,真的超久沒用到了…(⊙_⊙洒宝;)…
按照習(xí)慣通過看例子進(jìn)行了解吧。
例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"]萌京,明顯可以看出這里并沒有按照數(shù)字大小排列雁歌,而是以字符串的形式按照首字母依次排序的
例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"]
完。