按字符串属性排序对象

  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){
  24. var x = a.type.toLowerCase();
  25. var y = b.type.toLowerCase();
  26. if (x < y) {return -1;}
  27. if (x > y) {return 1;}
  28. return 0;
  29. });
  30. displayCars();
  31. }
  32.  
  33. function displayCars() {
  34. document.getElementById("demo").innerHTML =
  35. cars[0].type + " " + cars[0].year + "<br>" +
  36. cars[1].type + " " + cars[1].year + "<br>" +
  37. cars[2].type + " " + cars[2].year;
  38. }
  39. </script>
  40.  
  41. </body>
  42. </html>