是否存在反向逻辑空值赋值(reverse nullish assignment)运算符?
实现方案
你要的逻辑可以通过两种简洁的方式实现,都不需要显式写if代码块,完全兼容NodeJS运行环境:
方案1:原生一行写法(无需额外依赖)
利用!= null判断过滤null/undefined,配合短路逻辑实现条件赋值:
// 通用写法,适配变量、对象属性全场景 newValue != null && (target = newValue)
对应你的示例代码可以直接改写为:
let iceCream = { flavor: 'chocolate' } const foo = 2.5 const bar = undefined; bar != null && (iceCream.price = bar) // 条件不成立,不执行赋值,iceCream不会新增price属性 console.log(iceCream.price) // 输出undefined(JS访问不存在的对象属性默认返回undefined,不会抛出错误) foo != null && (iceCream.price = foo) // 条件成立,执行赋值 console.log(iceCream.price) // 输出2.5 bar != null && (iceCream.price = bar) // 条件不成立,不执行赋值 console.log(iceCream.price) // 输出2.5
如果是已经声明过的普通变量,还可以用更短的空值合并写法:
let x = 1 x = undefined ?? x // 相当于x = x,值保持1 x = 3 ?? x // x更新为3
注意:对象属性场景不要用上述空值合并写法,否则即使右值为nullish,也会给对象新增值为
undefined的属性,不符合你的需求。
方案2:封装工具函数(更贴近自定义运算符的使用体验)
如果频繁用到这个逻辑,可以封装通用工具函数复用:
function assignIfNotNullish(target, key, value) { value != null && (target[key] = value) }
使用方式:
assignIfNotNullish(iceCream, 'price', bar) // 不执行赋值 assignIfNotNullish(iceCream, 'price', foo) // 赋值成功
内容的提问来源于stack exchange,提问作者Proxycon
相关产品推荐
相关产品推荐

