json 数据排序Demo

作者: JONE 分类: 编程 发布时间: 2021-10-18 10:12
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>

<p id="demo">单击按钮降序排列数组。</p>
<button onclick="myFunction()">二维 点我升序</button>
<button onclick="myFunction2()">二维 点我降序</button>
<button onclick="myFunction3()">一维 点我升序</button>
<script>

var points = [
{name: '北京',value: '555',sort:1},
{name: '天津',value: '1000',sort:11},
{name: '上海',value: '100',sort:10},
{name: '重庆',value: '100',sort:91},
{name: '河北',value: '600',sort:1},
{name: '河南',value: '400',sort:'-1'},

];

var points2 = [11,2,3,45];

var field = 'sort';

function up(x,y){
return x[field]-y[field]
}

function down(x,y){
return y[field]-x[field]
}

function up2(x,y){
return x-y
}


function myFunction(){

points.sort(up);
console.log(points)

var x=document.getElementById("demo");
var str = JSON.stringify(points)
x.innerHTML=str;
}

function myFunction2(){

points.sort(down);
console.log(points)

var x=document.getElementById("demo");
var str = JSON.stringify(points)
x.innerHTML=str;
}

function myFunction3(){

points2.sort(up2);
console.log(points2)

var x=document.getElementById("demo");
var str = JSON.stringify(points2)
x.innerHTML=str;
}
</script>

</body>
</html>