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)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
写成类
<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>