在数组对象中,对某个类进行sort排序

var testArr = [
    { id: 1, name: 'cs', age: 18 },
    { id: 2, name: 'zs', age: 15 },
    { id: 3, name: 'ls', age: 20 },
    { id: 4, name: 'ww', age: 16 }   
]

function toSort(propertyName) {
    return function(a, b) {
        return a[propertyName] - b[propertyName]    // 升序
        // return b[propertyName] - a[propertyName]    // 降序
    }
}

console.log(testArr.sort(toSort('age')))    // 按照年龄升序
console.log(testArr.sort(toSort('name')))    // 按照姓名的ASCII码值升序

发布了18 篇原创文章 · 获赞 5 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/Yw_better/article/details/102754126