JavaScript-?.、??、??=、,运算符

?.(可选链语法)

代码例子

/* 测试?运算符 */
const test = {
    a: undefined,
    b: null,
    c: 'woshiceshi'
}

console.log("测试?运算符:")
// undefined null null 'woshiceshi' undefined undefined undefined
console.log(test?.a, test?.b, test.b, test?.c, test.d, test.d?.a, test.b?.a)
// undefined undefined undefined
console.log(null?.a, undefined?.b, "fadsf"?.c)

总结

  • 在非对象的变量中使用?.,就会返回undefined

??(双问号语法)

代码例子

/* 测试??运算符 */
const _a0 = undefined ?? '右边';
const _b0 = null ?? '右边';
const _c0 = '左边' ?? '右边';
console.log("测试??运算符:")
// 右边 右边 左边 false
console.log(_a0, _b0, _c0)

总结

  • 如果在??左边是null或者undefined的时候,返回右边的结果。

??=

代码例子

/* 测试??=运算符 */
const _test = {
    _a1: undefined,
    _b1: null,
    _c1: '左边',
    _d1: false,
}
_test._a1 ??= '右边';
_test._b1 ??= '右边';
_test._c1 ??= '右边';
_test._d1 ??= '右边';
console.log("测试??=运算符:")
// 右边 右边 左边 false
console.log( _test._a1, _test._b1, _test._c1, _test._d1)

总结

  • 注意:在nodejs v14.17.5的版本下,使用??=会报错;
  • ??=就是当左边是null或者undefined的时候,赋值右边的结果。

,

代码例子

/* 测试 , 运算符 */
const a = (1, 2, 3);
const b = (1, (4, 6));
const c = ((4, 6), 9);
const d1 = () => {
    let temp = 1;
    return temp++, temp--;
}
const d2 = () => {
    let temp = 1;
    return temp++, --temp;
}
const d3 = () => {
    let temp = 1;
    return ++temp, --temp;
}
const e = ((4, 6), 9 + 1);
// 这里还需考虑++ -- 的问题
// 3 6 9 2 1 1 10
console.log(a, b, c, d1(), d2(), d3(), e);

总结

  • ,运算符从左到右依次计算,然后返回,最右边的结果。
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值