array排序(按数组中对象的属性进行排序)
使用array.sort()对数组中对象的属性进行排序
<template> <div> <a @click="sortArray()">降序</a> </div> </template> <script> const oldArray = [{id: 1, name: 'Bek', age: '28'}, {id: 2, name: 'Evan', age: '12'}, {id: 3, name: 'John', age: '34'}] export default{ methods: { sortArray() { let newArray = oldArray.sort(this.compara('age')) console.log('newArray', newArray) }, // 降序 要按哪个属性排序 property compara(property) { return function (object1, object2) { let val1 = object1[property] let val2 = object2[property] if (val1 > val2) { return -1 } else if (val1 < val2) { return 1 } else { return 0 } } } } } </script>