在代码中出现不可预测的行为是不好的,但是如果你有这种行为,你需要处理它。 例如,常见错误TypeError,试获取undefined/null等属性,就会报这个错误。 | const found = [{ name: "Alex" }].find(i => i.name === 'Jim')
console.log(found.name)
// TypeError: Cannot read property 'name' of undefined
|
我们可以这样避免它: [size=1em]1
[size=1em]2
[size=1em]3
[size=1em]4
| [size=1em][size=1em]const found = [{ name: "Alex" }].find(i => i.name === 'Jim') || {}
[size=1em]
[size=1em]console.log(found.name)
[size=1em]// undefined
|
|