当调用不在对象中的键时,将返回 undefined。我想返回一个我指定的字符串而不是未定义的字符串。例如
let obj = {
key1: 'key1'
}
let res = obj.key2;
console.log(res);
I want console.log (res)
回来“找不到钥匙”, not undefined
.
这可能吗?
你可以采取空合并运算符??,它尊重其他falsy值比undefined
or null
.
let obj = { key1: 'key1' },
res = obj.key2 ?? 'key2 not found';
console.log(res);
If undefined
/null
是真实值,应提前检查密钥。
let obj = { key1: null },
res = 'key1' in obj ? obj.key1 : 'key2 not found';
console.log(res);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)