下面是js代碼:(請將其保存為sortJson.js)
$(document).ready(function () { //對json進行降序排序函數(shù) var colId="age" var desc = function(x,y) { return (x[colId] < y[colId]) ? 1 : -1 } //對json進行升序排序函數(shù) 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)); });
下面是html代碼:
<!DOCTYPE html> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type="text/javascript" src="http://lib.sinaapp.com/js/jquery/1.7.2/jquery.min.js"></script> <script type="text/javascript" src="sortJson.js"></script> </head> <body> </body> </html>
下面是排序的結(jié)果:
以上所述是小編給大家介紹的Json按某個鍵的值進行排序,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對武林網(wǎng)網(wǎng)站的支持!
新聞熱點
疑難解答