4-1升序

  1. arr.sort((a,b)=>{
  2. return a-b;
  3. })

4-2降序

  1. arr.sort((a,b)=>{
  2. return b-a;
  3. })

例子
实现数组的排序

  1. var arr=[4,7,1,3,14];
  2. //升序
  3. arr.sort((a,b)=>{
  4. return a-b;
  5. })
  6. console.log(arr);//[1,3,4,7,14]
  7. //降序
  8. arr.sort((a,b)=>{
  9. return b-a;
  10. })
  11. console.log(arr);//[14,7,4,3,1]

实现数组中元素的排序

  1. var students=[
  2. {name:"zhang",age:20},
  3. {name:"li",age:18},
  4. {name:"wang",age:9},
  5. {name:"陈",age:14},
  6. ]
  7. //升序
  8. var result=students.sort((a,b)=>{
  9. return a["age"]-b["age"];
  10. })
  11. console.log(result);
  12. //降序
  13. var result=students.sort((a,b)=>{
  14. return b["age"]-a["age"];
  15. })
  16. console.log(result);

实现指定条件排序

  1. <button id="like">通过好评数排序</button>
  2. <button id="price">通过价格排序</button>
  3. <script>
  4. var like=document.getElementById("like");
  5. var price=document.getElementById("price");
  6. var sales=[
  7. {name:"张三",like:60,distance:1000,price:10},
  8. {name:"张三",like:30,distance:100,price:40},
  9. {name:"张三",like:20,distance:500,price:6},
  10. ]
  11. //升序
  12. function addOrder(arr,value){
  13. var res=arr.sort((a,b)=>{
  14. return a[value]-b[value];
  15. })
  16. return res;
  17. }
  18. like.onclick=function(){
  19. console.log(addOrder(sales,"like"))
  20. }
  21. price.onclick=function(){
  22. console.log(addOrder(sales,"price"))
  23. }
  24. </script>