1.升序

语法:arr.sort((a,b)=>{
return a-b;
})

  1. var arr = [4,7,1,3,14]; //[1,3,4,7,14]
  2. var res = arr.sort((a,b)=>{
  3. return a-b;
  4. })
  5. console.log(res)//[1,3,4,7,14]

2.降序

语法: arr.sort((a,b)=>{
return b-a
})

  1. var arr = [4,7,1,3,14];
  2. var res = arr.sort((a,b)=>{
  3. return b-a;
  4. })
  5. console.log(res)//[14,7,4,3,1]

排序例子

  1. <script>
  2. var students = [
  3. {name:"zhang",age:20},
  4. {name:"li",age:18},
  5. {name:"wang",age:9},
  6. {name:"chen",age:14},
  7. ]
  8. /*
  9. 根据年龄升序
  10. 根据年龄降序
  11. */
  12. var result = students.sort((a,b)=>{
  13. return a["age"]-b["age"]
  14. })
  15. console.log(result)
  16. </script>
  1. <button id="like">通过好评排序</button>
  2. <button id="price">通过价格排序</button>
  3. <script>
  4. var like = document.getElementById("like");
  5. var sales = [
  6. { name: "张三", like: 60, distance: 1000, price: 10 },
  7. { name: "张三", like: 30, distance: 100, price: 40 },
  8. { name: "张三", like: 20, distance: 500, price: 6 },
  9. ]
  10. /* 升序 */
  11. function addOrder(arr, value) {
  12. if (Array.isArray(arr)) {
  13. var res = arr.sort((a, b) => {
  14. return a[value] - b[value];
  15. })
  16. return res;
  17. }else{
  18. return null;
  19. }
  20. }
  21. like.onclick = function () {
  22. console.log(addOrder(sales, "like"))
  23. }
  24. price.onclick = function () {
  25. console.log(addOrder(sales, "price"))
  26. }
  27. </script>