js运⽤sort对json数组进⾏排序
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
js获取json的key和value}
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>
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论