javascript中??和?的区别

在JavaScript中,`??` 和 `?` 是两个不同的操作符,具有不同的用途和行为。

  • `??` 操作符(Nullish Coalescing Operator)

        `??` 操作符用于判断一个表达式是否为 `null` 或 `undefined`,如果是,则返回一个默认值。它的语法如下:

const result = expression1 ?? expression2;

如果 `expression1` 的值为 `null` 或 `undefined`,则 `result` 的值为 `expression2`;否则,`result` 的值为 `expression1`。 例如:

const name = null; 
const defaultName = "John"; 
const result = name ?? defaultName; 
console.log(result); // 输出 "John"

在这个例子中,`name` 的值为 `null`,所以 `result` 的值为 `defaultName`,即 "John"。

  • `?` 操作符(Optional Chaining Operator)

`?` 操作符用于访问一个可能为 `null` 或 `undefined` 的对象的属性或方法,以避免出现错误。

它的语法如下:

const result = object?.property; 

 如果 `object` 不为 `null` 或 `undefined`,则返回 `property` 的值;否则,返回 `undefined`。 例如:

const person = { name: "John", age: 30 }; 
const result = person?.name; 
console.log(result); // 输出 "John

 在这个例子中,`person` 对象存在,并且有一个 `name` 属性,所以 `result` 的值为 "John"。

  • 总结
  1. `??` 操作符用于提供默认值,当左侧表达式为 `null` 或 `undefined` 时使用右侧表达式作为结果;
  2. `?` 操作符用于安全地访问可能为 `null` 或 `undefined` 的对象的属性或方法,避免出现错误。
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值