数组排序会影响原数组
数据区定义数组数据:
files: [
{id: "53", sexindex: "女", age: "1", experienceindex: "1", name: "小乔"},
{id: "44", sexindex: "女", age: "12", experienceindex: "3", name: "光头强", eid: "0"},
{id: "51", sexindex: "女", age: "18", experienceindex: "10", name: "红太狼", eid: "0"},
{id: "42", sexindex: "女", age: "21", experienceindex: "1", name: "熊大", eid: "0"},
{id: "48", sexindex: "女", age: "15", experienceindex: "7", name: "土拨鼠", eid: "0"},
{id: "47", sexindex: "女", age: "66", experienceindex: "6", name: "毛毛", eid: "0"},
{id: "54", sexindex: "女", age: "58", experienceindex: "2", name: "大桥", eid: "0"},
{id: "45", sexindex: "女", age: "31", experienceindex: "4", name: "跳跳", eid: "0"},
{id: "52", sexindex: "女", age: "51", experienceindex: "11", name: "慢羊羊", eid: "0"},
{id: "43", sexindex: "女", age: "18", experienceindex: "2", name: "熊二", eid: "0"},
{id: "50", sexindex: "女", age: "19", experienceindex: "9", name: "灰太狼", eid: "0"},
{id: "49", sexindex: "女", age: "17", experienceindex: "8", name: "喜羊羊", eid: "0"},
{id: "55", sexindex: "女", age: "15", experienceindex: "3", name: "武则天", eid: "0"},
{id: "46", sexindex: "女", age: "36", experienceindex: "5", name: "吉吉", eid: "0"}
]
根据一个条件排序
// 方法一
files.sort((a,b)=>{
return a.age-b.age //升序
})
console.log(files);
// 方法二
function sortBy (prop) {
return function (obj1, obj2) {
var val1 = obj1[prop];
var val2 = obj2[prop];
//判断是不是数值型
if (!isNaN(Number(val1)) && !isNaN(Number(val2))) {
val1 = Number(val1);
val2 = Number(val2);
}
if (val1 < val2) {
return -1; //不排序
} else if (val1 > val2) {
return 1; //排序
} else {
return 0; //相等
}
}
}
this.files.sort(sortBy("age"));
console.log(this.files);
根据多个条件排序
多个条件排序可使用arguments属性。
arguments属性