数组sort方法实现列表的正序和倒序
<!DOCTYPE html
>
<html lang
="en">
<head
>
<meta charset
="UTF-8">
<meta name
="viewport" content
="width=device-width, initial-scale=1.0">
<title
>Document
</title
>
<style
>
table
{
margin
: 0 auto
;
border
: 1px solid #ccc
;
border
-spacing
: 0;
}
th
,
td
{
width
: 200px
;
text
-align
: center
;
border
: 1px solid #ccc
;
}
</style
>
</head
>
<body
>
<table
>
<thead
>
<tr
>
<th
>姓名
</th
>
<th
>年龄
</th
>
<th
>性别
</th
>
<th
>分数
</th
>
</tr
>
</thead
>
<tbody
>
</tbody
>
</table
>
<button
>按照分数排序
</button
>
<script
>
var tbody
= document
.querySelector('tbody');
var btn
= document
.querySelector('button');
var GZ2006 = [{
name
: "刘德华",
age
: 20,
sex
: '男',
score
: 99
}, {
name
: "张学友",
age
: 22,
sex
: '男',
score
: 10
}, {
name
: "黎明",
age
: 26,
sex
: '男',
score
: 55
}, {
name
: "梁朝伟",
age
: 60,
sex
: '男',
score
: 20
}];
function render() {
var arr
= GZ2006.map((item
) => {
return '<tr><td>' + item
.name
+ '</td><td>' + item
.age
+ '</td><td>' + item
.sex
+ '</td><td>' + item
.score
+ '</td></tr>'
})
tbody
.innerHTML
= arr
.join('');
}
render();
var flag
= true;
btn
.onclick = function() {
if (flag
) {
GZ2006.sort((a
, b
) => {
return a
.score
- b
.score
;
})
render();
} else {
GZ2006.sort((a
, b
) => {
return b
.score
- a
.score
;
})
render();
}
flag
= !flag
;
}
</script
>
</body
>
</html
>
转载请注明原文地址:https://tech.qufami.com/read-270.html