[英]How can I reuse function by making it more flexible
我正在嘗試在我的 NodeJs Api 中構建一個 function ,它將返回滿足某些條件的數組中的對象。 在這種情況下,我使用findIndex
來執行此操作。 我的問題是能夠重用 function 有沒有辦法在data.phones.findIndex
中傳遞[phones]
之類的值,這樣如果我想要電子郵件,我可以只傳遞電子郵件而不必創建新的 function? 此外,我可以在item.type
中傳遞[type]
之類的字段嗎? 至於電話部分,我知道我可以這樣稱呼它
getWorkPhone(myObj.phones, 'Work')
並刪除phones
並使其成為data.findIndex
。 最后一部分是我如何獲得所有索引,因為findIndex
只返回第一個匹配項,所以如果有多個索引?
const getWorkPhone = (data, myValue) => {
const index = data.phones.findIndex(item => item.type === myValue && item.dflt === true)
console.log(index)
console.log(data.phones[index].number)
}
我認為您需要filter
來獲取數組中滿足特定條件的所有“事物”的列表。
所以也許,這是一個很好的語法:
const workNumbers = numbers.filter(phoneFilter('work'));
那么phoneFilter
function 的職責是返回一個與filter
一起使用的 function 。
function phoneFilter(type) {
return (item) => item.type === type;
}
當然,這與在線執行所有操作並沒有什么不同,但它確實增加了一些不錯的語義含義。 在沒有輔助函數的情況下做所有事情看起來像這樣(我認為這仍然很明顯/可讀):
const workNumbers = numbers.filter(item => item.type === 'work');
第三種方法是定義一個 function進行.filter()
調用和過濾本身,但我認為它的組合不太好:
function myPhoneFilter(numbers, type) {
return numbers.filter(item => item.type === type);
}
const workNumbers = myPhoneFilter(numbers, 'work');
對於像這樣的簡單用例,我什至不會費心編寫輔助函數,因為內聯版本已經很明顯了:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.