0%

利用jQuery 对对象数组排序

利用jQuery对对象进行排序。

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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
<title>jQuery数组和字符串--对象数组排序</title>
<script type="text/javascript" src="../jquery-1.3.2.min.js"></script>

<script type="text/javascript">

<!--
$(
function()
{
var students =[
{'sid':'ST001','sname':'张三','sage':18},
{'sid':'ST004','sname':'赵六','sage':23},
{'sid':'ST002','sname':'李四','sage':42},
{'sid':'ST003','sname':'王五','sage':35}
];
//表格显示
$.each(students,
function(index, value)
{
$('#ia').append('<tr><td>' + value.sid +
'</td><td>' + value.sname +
'</td><td>' + value.sage + '</td></tr>');
}
);
//按照SID排序
var sidOrder = students.sort(
function(a, b)
{
if(a.sid < b.sid) return -1;
if(a.sid > b.sid) return 1;
return 0;
}
);
$.each(sidOrder,
function(index, value)
{
$('#ib').append('<tr><td>' + value.sid +
'</td><td>' + value.sname +
'</td><td>' + value.sage + '</td></tr>')
}
);
//按照SAGE排序
var sageOrder = students.sort(
function(a, b)
{
return (a.sage - b.sage);
}
);
$.each(sageOrder,
function(index, value)
{
$('#ic').append('<tr><td>' + value.sid +
'</td><td>' + value.sname +
'</td><td>' + value.sage + '</td></tr>')
}
);
}
);
//-->
</script>
</head>
<body>
<h5>未排序对象数组:</h5>
<table id='ia' border="1"></table>

<h5>按照SID排序对象数组:</h5>
<table id='ib' border="1"></table>

<h5>按照SAGE排序对象数组:</h5>
<table id='ic' border="1"></table>

</body>
</html>