zoukankan      html  css  js  c++  java
  • JavaScript双重排序

    前言:正好这两天正在做一个功能,需要在前台进行排序展示,因为是动态的,后台排序不能搞定,只能咋前台通过JS来进行排序展示,所以我们用sort()来解决这个问题,sort不仅能给数组,对象,集合进行简单的排序,还能进行双重,多重排序。哈哈.... 不讲废话了

    JavaScript双重排序

    1. 语法详解

      Array.sort((a, b) =>{})

      JS中sort 函数需要传入一个函数,例如 sort((a,b)=>{ }). a, b 为需要排序的数组的两个值,可以根据x, y的大小进行返回:

      负值,如果所传递的第一个参数比第二个参数小。

      零,如果两个参数相等。

      正值,如果第一个参数比第二个参数大。

    2. 示例

     1 sortName(sortObj){
     2     // this.addOrderData.product_list.sort(this.compare(sortObj.prop, sortObj.order))
     3     this.addOrderData.product_list.sort((a, b)=>{
     4  
     5         if (sortObj.order == 'ascending') {
     6             if (a["product_name"] === b["product_name"]) {
     7                 return a["lot"] > b["lot"] ? 1 : a["lot"] < b["lot"] ? -1 : 0;
     8             } else {
     9                 return a["product_name"] > b["product_name"] ? 1 : -1;
    10             }
    11         }else {
    12             if (a["product_name"] === b["product_name"]) {
    13                 return a["lot"] > b["lot"] ? 1 : a["lot"] < b["lot"] ? -1 : 0;
    14             } else {
    15                 return a["product_name"] < b["product_name"] ? 1 : -1;
    16             }
    17         }
    18  
    19     })
    20  
    21 }

    Js中sort 函数需要传入一个函数,例如 sort(function(x,y){ }). x, y 为需要排序的数组的两个值,可以根据x, y的大小进行返回:

    负值,如果所传递的第一个参数比第二个参数小。

    零,如果两个参数相等。

    正值,如果第一个参数比第二个参数大。

     

    3.注意事项

    在IE中JS不支持Array.sort((a, b) =>{})可换成Array.sort(function(a, b) {})

  • 相关阅读:
    1130 host '***' is not allowed to connect to this MySQL server
    签名时出错,未能对....ext签名。SignTool Error: No certificates...
    C# 进制转换(二进制、十六进制、十进制互转)
    在安装32位Oracle客户端组建的情况下以64位模式运行
    Vue中引入jQuery
    sql server数据库分离时,数据库右侧显示(单个用户)
    解决Typora图片显示问题
    Ruby日文手册翻译1
    Boost Graph Library 库小结1
    归并排序
  • 原文地址:https://www.cnblogs.com/JamelAr/p/12011444.html
Copyright © 2011-2022 走看看