var array = [ {name: ‘a‘, phone: 1}, {name: ‘b‘, phone: 5}, {name: ‘d‘, phone: 3}, {name: ‘c‘, phone: 4} ] array.sort(getSortFun(‘desc‘, ‘phone‘)); function getSortFun(order, sortBy) { var ordAlpah = (order == ‘asc‘) ? ‘>‘ : ‘<‘; var sortFun = new Function(‘a‘, ‘b‘, ‘return a.‘ + sortBy + ordAlpah + ‘b.‘ + sortBy + ‘?1:-1‘); return sortFun; } alert(JSON.stringify(array));
数组本身有sort方法,可以指定排序函数,因此可以动态生成一个排序函数来完成对按指定对象属性排序的需求;
注意:sort后原数组序列会发生变化!!
JS中:json对象数组按对象属性排序
时间: 2024-10-05 08:54:01