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

JavaScript使用三元运算符在函数返回undefined时返回默认值

给定前提

现有不可修改的函数如下:

function isTastyCheese(cheeseName: string) {
    const TastyCheeses = ['camembert', 'maroilles']
    if (TastyCheeses.includes(cheeseName)) {
        return 'yes so tasty'
    }
    return undefined
}

需求为:调用上述函数时,若匹配到对应奶酪则返回函数给出的'yes so tasty'结果,否则返回兜底文案'no taste like sh*t',必须使用三元运算符实现,不得修改原函数。

具体实现

原函数的两类返回值刚好对应JavaScript三元判断的真假分支:

  • 匹配成功返回非空字符串,属于真值,会命中三元的真分支
  • 匹配失败返回undefined,属于假值,会命中三元的假分支

直接按逻辑书写即可:

const answerCamembert = isTastyCheese('camembert') ? isTastyCheese('camembert') : 'no taste like sh*t' 
const answerCantal = isTastyCheese('cantal') ? isTastyCheese('cantal') : 'no taste like sh*t'

console.log(answerCamembert) // 输出:'yes so tasty'
console.log(answerCantal) // 输出:'no taste like sh*t'

如果不希望重复调用函数(避免后续函数逻辑变重后产生不必要的性能消耗),可以先缓存函数返回结果再做三元判断,写法更高效:

// 仅调用一次isTastyCheese获取卡门贝尔奶酪的结果
const camembertRes = isTastyCheese('camembert')
const answerCamembert = camembertRes ? camembertRes : 'no taste like sh*t'

// 仅调用一次isTastyCheese获取康塔勒奶酪的结果
const cantalRes = isTastyCheese('cantal')
const answerCantal = cantalRes ? cantalRes : 'no taste like sh*t'

补充:空值合并运算符??可以把逻辑简化为isTastyCheese('xxx') ?? 'no taste like sh*t',但该写法不属于三元运算符范畴,不符合题目要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 02:18:14