You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript中使用arr.map(elem => dict[elem])时如何返回null而非undefined

简洁实现方案:用空值合并运算符替换undefined为null

你可以利用TypeScript支持的**空值合并运算符(??)**来简洁地实现这个需求,它专门用于处理null/undefined的场景,比传统条件判断更简洁直观。

修改后的函数如下:

function recode(arr: string[], dict: Record<string, string>): (string | null)[] {
  return arr.map(el => dict[el] ?? null);
}

为什么这个方案可行?

  • 当数组元素el在字典dict中存在对应键时,dict[el]会返回匹配的字符串值;
  • 当el不存在于字典中时,dict[el]会返回undefined,此时??运算符会触发右侧的null,把结果替换成你期望的null;
  • 我们还调整了函数的返回类型注解,从原来的(string | undefined)[]明确为(string | null)[],让TypeScript的类型检查更精准,也符合你的输出预期。

用你的测试代码验证:

const myArr: string[] = ['eggplant', 'tomato', 'carrot', 'cabbage'];
const myDictionary: Record<string, string> = {
  eggplant: 'purple',
  tomato: 'red',
  carrot: 'orange'
};

console.log(recode(myArr, myDictionary)); 
// 输出:["purple", "red", "orange", null]

如果你的数组元素可能包含非字符串类型(比如保留原来的any[]参数),也可以用Object.prototype.hasOwnProperty做更严谨的键存在性判断,但对于你当前的场景,??已经足够简洁且完全满足需求。

内容的提问来源于stack exchange,提问作者Emman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 14:37:39