1 Optional Chaining(可选链)
const user = {
name: 'Tom',
address: {
city: 'ZhengZhou'
}
}
user.address?.city
user.address?.city?.length
// 结合 ?.[] 的方式访问相当于 user.address['city']
user.address?.['city']
console.log('house', user.address?.house?.z)
// 结合 delete 语句使用,仅在 user.address.city 存在才删除
delete user.address?.city
2 Nullish Coalescing(空值合并)
逻辑或操作符(||)会在左侧为假值时返回右侧的操作符,例如我们传入一个属性为 enabled:0 我们期望输出左侧的值,则是不行的。
function Component(props) {
const enable = props.enabled || true; // true
}
Component({ enabled: 0 })
现在我们可以使用 空值合并操作符(??)来实现,仅当左侧为 undefined 或 null 时才返回右侧的值。
function Component(props) {
const enable = props.enabled ?? true; // 0
}
Component({ enabled: 0 })
网友评论