js多维数组的排序

1 二维数组的排序

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4     <meta charset="utf-8">
 5     <title>IFE JavaScript Task 01</title>
 6 </head>
 7 <body>
 8 
 9 <h3>污染城市列表</h3>
10 <ul id="aqi-list">
11 
12 </ul>
13 
14 <script type="text/javascript">
15 
16     var aqiData = [
17         ["北京", 95,[2]],
18         ["上海", 50,[3]],
19         ["福州", 10,[7]],
20         ["广州", 50,[4]],
21         ["成都", 90,[6]],
22         ["西安", 100,[5]]
23     ];
24 
25     (function () {
26         aqiData.sort(function(a,b){
27             return a[1]-b[1]});
28         var ul = document.getElementsByTagName("ul")[0];
29         for(var i=0; i<aqiData.length;i++){
30             //for循环添加只能一条。一定要注意+=
31             ul.innerHTML += "<li>"+""+i+"名:"+aqiData[i][0]+",pm2.5指数:"+aqiData[i][1]+"</li>";
32         }
33     })();
34 
35 </script>
36 </body>
37 </html>

2 三维数组排序

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4     <meta charset="utf-8">
 5     <title>IFE JavaScript Task 01</title>
 6 </head>
 7 <body>
 8 
 9 <h3>污染城市列表</h3>
10 <ul id="aqi-list">
11 
12 </ul>
13 
14 <script type="text/javascript">
15 
16     var aqiData = [
17         ["北京", 95,[2]],
18         ["上海", 50,[3]],
19         ["福州", 10,[7]],
20         ["广州", 50,[4]],
21         ["成都", 90,[6]],
22         ["西安", 100,[5]]
23     ];
24 
25     (function () {
26         aqiData.sort(function(a,b){
27             return a[2][0]-b[2][0]});
28         var ul = document.getElementsByTagName("ul")[0];
29         for(var i=0; i<aqiData.length;i++){
30             //for循环添加只能一条。一定要注意+=
31             ul.innerHTML += "<li>"+""+i+"名:"+aqiData[i][0]+",pm2.5指数:"+aqiData[i][1]+"</li>";
32         }
33     })();
34 
35 </script>
36 </body>
37 </html>

3 一个比较怪的方法(排序二维)

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4     <meta charset="utf-8">
 5     <title>IFE JavaScript Task 01</title>
 6 </head>
 7 <body>
 8 
 9 <h3>污染城市列表</h3>
10 <ul id="aqi-list">
11 
12 </ul>
13 
14 <script type="text/javascript">
15 
16     var aqiData = [
17         ["北京", 95,[2]],
18         ["上海", 50,[3]],
19         ["福州", 10,[7]],
20         ["广州", 50,[4]],
21         ["成都", 90,[6]],
22         ["西安", 100,[5]]
23     ];
24 
25     (function () {
26 
27         //---------------
28         var result = [];
29         function City(name,num) {
30             this.name=name;
31             this.num = num;
32         }
33         for(var i = 0; i<aqiData.length;i++){
34             result.push(new City(aqiData[i][0],aqiData[i][1]));
35         }
36         console.log(result);
37         result.sort(function(a,b){
38             return a.num-b.num});
39         var ul = document.getElementsByTagName("ul")[0];
40         for(var i=0; i<result.length;i++){
41             //for循环添加只能一条。一定要注意+=
42             ul.innerHTML += "<li>"+""+i+"名:"+result[i].name+",pm2.5指数:"+result[i].num+"</li>";
43         }
44 
45     })();
46 
47 </script>
48 </body>
49 </html>

 

posted @ 2017-02-09 11:18  武侯668  阅读(5339)  评论(0编辑  收藏  举报