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

JavaScript中无需调用函数的条件判断简写方式有哪些?

首先给出两种符合要求的无函数调用的简洁写法,可根据你的实际逻辑需求选择:

1. 和原代码逻辑完全等价的写法(所有假值都返回0)

原代码的判断规则是只要areaValueInDollars为任意假值(包括0、空字符串、false、null、undefined)就返回0,你可以直接用逻辑或运算符||简化:

const currentValue = this.props.book.location.areaValueInDollars || 0;

2. 更符合业务常用场景的写法(仅null/undefined时返回0)

如果你是要做属性兜底,不希望把合法的0、空字符串等有效值也覆盖掉,可以用ES2020新增的空值合并运算符??:

const currentValue = this.props.book.location.areaValueInDollars ?? 0;

如果你的属性链路中某一层可能不存在(比如this.props.book或者location有可能为undefined/null),还可以搭配可选链运算符?.使用,避免读取属性时报错,同样不需要调用任何函数:

// 仅兜底null/undefined场景
const currentValue = this.props.book?.location?.areaValueInDollars ?? 0;

// 所有假值都兜底到0
const currentValue = this.props.book?.location?.areaValueInDollars || 0;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 12:45:02