代码之家  ›  专栏  ›  技术社区  ›  Aragorn

参数用于筛选数组的属性

  •  0
  • Aragorn  · 技术社区  · 7 年前

    我有两个几乎相同的函数,只是它们比较数组中对象的不同属性。有没有办法将该属性作为参数,然后将这两个函数合并为一个?

    第一个函数,比较属性 credit

      public filterByCredit(filter: string) {
    
        switch (filter) {
          case 'Non-blanks':
            this.filteredTxs = this.localTransactions.filter(tx => tx.credit);
            break;
          case 'Blanks':
            this.filteredTxs = this.localTransactions.filter(tx => !tx.credit);
            break;
          case '> 500':
            this.filteredTxs = this.localTransactions.filter(tx => tx.credit > 500);
            break;
        }
    
      }
    

    比较属性的第二个函数 debit

    public filterByDebit(filter: string) {
        switch (filter) {
          case 'Non-blanks':
            this.filteredTxs = this.localTransactions.filter(tx => tx.debit);
            break;
          case 'Blanks':
            this.filteredTxs = this.localTransactions.filter(tx => !tx.debit);
            break;
          case '> 500':
            this.filteredTxs = this.localTransactions.filter(tx => tx.debit > 500);
            break;
        }
    
    3 回复  |  直到 7 年前
        1
  •  3
  •   Zooly    7 年前

    你可以通过考试 key

    public filterByDebit(filter: string, key: string) {
        switch (filter) {
            case 'Non-blanks':
                this.filteredTxs = this.localTransactions.filter(tx => tx[key]);
                break;
            case 'Blanks':
                this.filteredTxs = this.localTransactions.filter(tx => !tx[key]);
                break;
            case '> 500':
                this.filteredTxs = this.localTransactions.filter(tx => tx[key] > 500);
                break;
        }
    }
    
        2
  •  1
  •   Ashish Ranjan    7 年前

    只需发送另一个参数:

    public filterByCredetDebit(filter, creditOrDebit) {
        switch (filter) {
            case 'Non-blanks':
                this.filteredTxs = this.localTransactions.filter(tx => tx[creditOrDebit]);
                break;
            case 'Blanks':
                this.filteredTxs = this.localTransactions.filter(tx => !tx[creditOrDebit]);
                break;
            case '> 500':
                this.filteredTxs = this.localTransactions.filter(tx => tx[creditOrDebit] > 500);
                break;
        }
    }
    
        3
  •  1
  •   brk    7 年前

    credit debit

    public filterByType(filter: string,type:string) {
      let __tp
      if(type==='credit'){
        __tp='credit'
      }
      else{
        __tp='debit'
      }
        switch (filter) {
          case 'Non-blanks':
            this.filteredTxs = this.localTransactions.filter(tx => tx[__tp]);
            break;
          case 'Blanks':
            this.filteredTxs = this.localTransactions.filter(tx => !tx[__tp]);
            break;
          case '> 500':
            this.filteredTxs = this.localTransactions.filter(tx => tx[__tp] > 500);
            break;
        }
    }
    
    推荐文章