Array.sort()方法是用來對數組項進行排序的 ,默認情況下是進行升序排列。sort() 方法可以接受一個 方法為參數。
sort()排序時每次比較兩個數組項都回執行這個參數,並把兩個比較的數組項作為參數傳遞給這個函數。當函數返回值為1的時候就交換兩個數組項的順序,否則就不交換。
var p = [5, 2, 3, 1, 7, 5, 6, 9, 6, 0]; function down(a, b) { return (a < b) ? 1 : -1 } p.sort(down) alert(p)
json排序
var p = [ {name:"kitty", age:12}, {name:"sonny", age:9}, {name:"jake", age:13}, {name:"fun", age:24} ] function down(x, y) { return (x.age < y.age) ? 1 : -1 } p.sort(down) var $text = "<div>" $.each(p, function (key, value) { var $div = "<div>" $.each(value, function (key, value) { $div += "<span>" + key + ":</span>" + "<span>" + value + "</span>" + " " }) $div += "</div>" $text = $text + $div }) $text += "</div>" $(".text").html($text)
寫成類
<script type="text/javascript"> $(document).ready(function () { var p = [ {name:"kitty", age:12, price:190}, {name:"sonny", age:9, price:390}, {name:"jake", age:13, price:42}, {name:"fun", age:24, price:210} ] var tablesort = { init:function (arry, parm, sortby) { this.obj = arry this.parm = parm this.b = sortby }, sot:function () { var $this = this var down = function (x, y) { return (eval("x." + $this.parm) > eval("y." + $this.parm)) ? -1 : 1 }//通過eval對json對象的鍵值傳參 var up = function (x, y) { return (eval("x." + $this.parm) < eval("y." + $this.parm)) ? -1 : 1 } if (this.b == "down") { this.obj.sort(down) } else { this.obj.sort(up) } },//排序 prin:function () { var $text = "<div>" $.each(this.obj, function (key, value) { var $div = "<div>" $.each(value, function (key, value) { $div += "<span>" + key + ":</span>" + "<span>" + value + "</span>" + " " }) $div += "</div>" $text = $text + $div }) $text += "</div>" $("html body").html($text) }//遍歷添加dom元素,添加dom } function _temp() { this.init.apply(this, arguments) } _temp.prototype = tablesort; var sort1 = new _temp(p, "price", "down") //建立對象 sort1.init(p, "age", "up");//初始化參數更改 sort1.sot() sort1.prin() }) </script>