给JSON数组 排序
本帖最后由 周大胖子 于 2018-10-19 10:38 编辑/**
* json对象数组按照某个属性排序:降序排列
* @param {Object} propertyName
*/
function compareDesc(propertyName) {
return function(object1, object2) {
var value1 = object1;
var value2 = object2;
if(value2 < value1) {
return -1;
} else if(value2 > value1) {
return 1;
} else {
return 0;
}
}
}
/**
* json对象数组按照某个属性排序:升序排列
* @param {Object} propertyName
*/
function compareAsc(propertyName) {
return function(object1, object2) {
var value1 = object1;
var value2 = object2;
if(value2 < value1) {
return 1;
} else if(value2 > value1) {
return -1;
} else {
return 0;
}
}
}
将 上面这个 复制到 你的JS中
向下面这样用
例子:
var students=[{name:"hhhh",age:16},{name:"ggggg",age:17},{name:"dsdsad",age:18}];
students.sort(compareDesc("age")); //按照年龄降序排列
students.sort(compareAsc("age")); //按照年龄升序排列
上面的有误! 没有转换成数字所以封装函数 应该是这么一句:
var value1 = Number(object1);
var value2 =Number(object2);
页:
[1]