js对对象数组的某一字段排序(前端网备份)

var friends = [

{avg1: 21, avg2: 95.2719, avg3: 0, avg4: 0, college: "经济与管理学院",},
{avg1: 28, avg2: 91.2719, avg3: 0, avg4: 0, college: "经济与管理学院",},
{avg1: 1, avg2: 97.2719, avg3: 0, avg4: 0, college: "经济与管理学院",},
];
var x = "avg1";
//之前出过的bug是a.x(是underfined)原因在a.x会把x当字符串解析,所以得a[x]
friends.sort(function (a, b) {
console.log(a[x])
if (a[x] < b[x]) {
return -1
}
if (a[x] > b[x]) {
return 1
}
return 0;
});
console.log(friends)

posted @ 2019-06-10 13:45  影思密达ing  阅读(1507)  评论(0编辑  收藏  举报