我有两个几乎相同的函数,除了它们比较数组内对象的不同属性。有没有一种方法可以将该属性作为参数,然后将这两个函数组合为一个函数?
第一个函数,它比较事务数组上的属性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;
}
最佳答案
您可以这样尝试。
向该函数中再添加一个参数,该参数接受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;
}
}
关于javascript - 参数用于过滤数组的属性,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53764287/