试了下这个是好使的:arr.sort(function(a,b){return a-b})可以把数组从小到大排序 var data=[ {name:"hhhh",age:17,else:200}, {name:"ssss",age:18,else:100} ] function compareSth(name){ return function(obj1,obj2){ var value1 = obj1[name]; var value2 = obj2[name]; if(value1 < value2){ return -1; }else if(value2 > value1){ return 1; }else{ return 0; } } } data.sort(compareSth("age")); console.log(data); data.sort(compareSth("else")); console.log(data); data.sort(compareSth("name")); console.log(data);那这个为啥不能按属性的大小排呐。。。看不出啥问题
1 回答
陪伴而非守候
TA贡献1757条经验 获得超8个赞
你确定?你的if 和else if的条件不是相同的吗
var data=[
{name:'iiii',age:20,else:300},
{name:"hhhh",age:17,else:200},
{name:"ssss",age:18,else:100}
]
function compareSth(name){
return function(obj1,obj2){
var value1 = obj1[name];
var value2 = obj2[name];
if(value1 < value2){
return -1;
}else if(value1 > value2){
return 1;
}else{
return 0;
}
}
}
console.log(data.sort(compareSth('age')));
你试一试,没问题的
添加回答
举报
0/150
提交
取消