// 示例代码:使用可选链操作符 (?.)
// 假设我们有一个嵌套的对象结构
const user = {
name: "Alice",
address: {
city: "Wonderland"
}
};
// 使用可选链操作符访问嵌套属性
console.log(user.address?.city); // 输出: Wonderland
// 如果中间的属性不存在,不会抛出错误,而是返回 undefined
console.log(user.address?.state); // 输出: undefined
// 对于函数调用也可以使用可选链操作符
const obj = {
func: () => "Hello"
};
console.log(obj.func?.()); // 输出: Hello
// 如果方法不存在,不会抛出错误,而是返回 undefined
console.log(obj.nonExistentFunc?.()); // 输出: undefined
?. 是 JavaScript 中的可选链操作符(Optional Chaining),它允许你在访问对象的嵌套属性时,如果某个中间属性不存在,则不会抛出错误,而是返回 undefined。undefined 而不是抛出错误。上一篇:js 刷新当前页面
下一篇:js 获取
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站