JavaScript中数组sort()方法使用例子
一、基本用法
function compare(val1, val2) {
if (val1 > val2) {
return 1
} else if (val1 == val2) {
return 0
} else {
return -1
}
}
var array = [0, 5, 4, 3, 9, 10]
console.log(array.sort(compare))
// 输出[0, 3, 4, 5, 9, 10]
二、根据对象属性对对象排序
function createComparisonFunction(propertyName) {
return function (object1, object2) {
let value1 = object1[propertyName]
let value2 = object2[propertyName]
if (value1 < value2) {
return -1
} else if (value1 > value2) {
return 1
} else {
return 0
}
}
}
let data = [
{
name: 'Links',
age: 28
},
{
name: 'Dolly',
age: 27
},
{
name: 'Rose',
age: 26
}
]
data.sort(createComparisonFunction("age"))
console.log(data)
// 输出
0: {name: "Rose", age: 26}
1: {name: "Dolly", age: 27}
2: {name: "Links", age: 28}
例子来自《JavaScript高级程序设计》(第3版)