在 JavaScript 中,当我们访问一个对象的属性时,如果该属性不存在,JavaScript 会抛出一个 TypeError 错误。
TypeError: Cannot read properties of null (reading 'xxx')
为了避免这种错误,ECMAScript 2020 引入了三个新的运算符:可选链运算符 ?.
、空值合并运算符 ??
和逻辑空赋值运算符 ??=
。
-
可选链运算符
?.
可选链运算符是一个简洁而有效的解决方案,用于检查给定属性是否存在。例如,如果你正在尝试访问嵌套在其他对象中的属性,并且该对象不存在,则可选链运算符允许你安全地避免错误。const person = { id: 10086, name: '阿凯', sex: '男', desc: null }; // 直接做法 console.log(person.desc.age); //TypeError console.log(person.desc && person.desc.age); //null // 使用可选链 console.log(person.desc?.age) // undefined // 使用深度可选链 console.log(person.desc?.address?.city); //undefined // 函数可选链 console.log(person.fun?.()); //undefined ```
-
空值合并运算符
??
空值合并运算符允许你为null
或undefined
的值提供默认值。这个运算符在许多情况下都很有用,例如当你尝试从对象中获取属性时,但该属性不存在。const person = { id: 10086, name: '阿凯', sex: '男', desc: null }; // 左侧值存在 console.log(person.desc ?? person.name) // 阿凯 // 左侧值为undefined console.log(person.skill ?? person.name) // 阿凯
-
逻辑空赋值运算符
??=
逻辑空赋值运算符允许你在左侧的值为null
或undefined
时,对其进行赋值。它可以帮助你简化代码,并减少检查左侧值是否为空的代码行。const person = { id: 10086, name: '阿凯', sex: '男', desc: null }; // 左侧值存在 console.log(person.id ??= person.name) // 10086 // 左侧值为null console.log(person.desc ??= 'default output') // default output // 左侧值为undefined console.log(person.skill ??= 'default output') // default output
总结:使用这些新的运算符可以使代码更简洁、更可读、更健壮,并减少在 JavaScript 中的错误。