我撰寫了一個簡單的函式來根據查找字典物件替換陣列中的值:
// typescript
function recode(arr: any[], dict: Record<string, string> ) {
return arr.map(el => dict[el])
}
它按預期作業。但是,我希望該函式null在查找字典中的陣列值不匹配時回傳。
所以現在如果我這樣做:
// array input
const myArr: string[] = ['eggplant', 'tomato', 'carrot', 'cabbage'];
// look-up dictionary
const myDictionary: Record<string, string> = {
eggplant: 'purple',
tomato: 'red',
carrot: 'orange'
};
function recode(arr: any[], dict: Record<string, string> ) {
return arr.map(el => dict[el])
}
// calling recode()
recode(myArr, myDictionary)
// returns
// ["purple", "red", "orange", undefined]
但我希望輸出是
// ["purple", "red", "orange", null]
考慮到我正在使用打字稿(不確定它會有所不同),是否有一種足夠簡單的方法來實作這一點?
打字稿 REPL
uj5u.com熱心網友回復:
您可以使用nullish 合并運算子 ( ??)來解決null以下情況undefined(并使用泛型型別引數從引數中推斷值的型別dict):
TS游樂場
const myArr: string[] = ['eggplant', 'tomato', 'carrot', 'cabbage'];
const myDictionary: Record<string, string> = {
eggplant: 'purple',
tomato: 'red',
carrot: 'orange'
};
function recode <T extends Record<string, any>>(
arr: readonly string[],
dict: T,
): (T[keyof T] | null)[] {
return arr.map(el => dict[el] ?? null);
}
const result = recode(myArr, myDictionary); // (string | null)[]
console.log(result);
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/436045.html
標籤:javascript 打字稿 功能 空值 不明确的
上一篇:創建一個函式以從每個子串列包含2個值的串列中洗掉或替換最后一個數字
下一篇:使用webpack動態加載圖片
