對JSON集合 某個鍵進行升序/降序排列
阿新 • • 發佈:2019-01-22
$(document).ready(function () { //對json進行降序排序函式 var colId="age" var desc = function(x,y) { return (x[colId] < y[colId]) ? 1 : -1 } //對json進行升序排序函式 var asc = function(x,y) { return (x[colId] > y[colId]) ? 1 : -1 } var arr2 = [ {name:"kitty", age:12}, {name:"sonny", age:9}, {name:"jake", age:13}, {name:"fun", age:24} ]; document.writeln("按age進行升序排序:<br>"); arr2.sort(asc); //升序排序 document.writeln(JSON.stringify(arr2)); document.writeln("<br>按age進行降序排序:<br>"); arr2.sort(desc); //降序排序 document.writeln(JSON.stringify(arr2)); });