当一个不在对象中的键被调用时,它返回undefined。我想返回一个我指定的字符串而不是未定义的。例如
let obj = {
key1: 'key1'
}
let res = obj.key2;
console.log(res);
我希望 console.log (res)
返回"key not found",而不是undefined
。
这可能吗?
最佳答案
你可以拿Nullish coalescing operator ??
,它尊重其他falsy值小于 undefined
或 null
。
let obj = { key1: 'key1' },
res = obj.key2 ?? 'key2 not found';
console.log(res);
如果undefined
/null
是实数,需要提前检查key。
let obj = { key1: null },
res = 'key1' in obj ? obj.key1 : 'key2 not found';
console.log(res);
关于javascript - 返回在 javascript 对象中找不到的键的默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66120189/