按数字属性排序对象

  1. <!DOCTYPE html>
  2. <html>
  3. <body>
  4.  
  5. <h1>JavaScript 数组排序</h1>
  6.  
  7. <p>点击按钮按年份对汽车进行排序:</p>
  8.  
  9. <button onclick="myFunction()">排序</button>
  10.  
  11. <p id="demo"></p>
  12.  
  13. <script>
  14. var cars = [
  15. {type:"BMW", year:2017},
  16. {type:"Audi", year:2019},
  17. {type:"porsche", year:2018}
  18. ];
  19.  
  20. displayCars();
  21.  
  22. function myFunction() {
  23. cars.sort(function(a, b){return a.year - b.year});
  24. displayCars();
  25. }
  26.  
  27. function displayCars() {
  28. document.getElementById("demo").innerHTML =
  29. cars[0].type + " " + cars[0].year + "<br>" +
  30. cars[1].type + " " + cars[1].year + "<br>" +
  31. cars[2].type + " " + cars[2].year;
  32. }
  33. </script>
  34.  
  35. </body>
  36. </html>