特殊符号: && 和 | | 和 ?? 和 ?作用详解

本文详细介绍了JavaScript中的条件运算符,包括问号(?:)用于判断是否存在并执行,双问号(??)用于判断是否为undefined或null并提供默认值,逻辑或(||)和逻辑与(&&)在条件判断中的应用。通过实例演示了这些运算符如何避免错误并简化代码,对于开发者来说是提高效率的重要工具。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

符号:?
作用:判断(?)前的内容是否存在,然后决定是否要执行(?)后的内容
适用场景:当不确定某个变量是否存在,并要对其进行遍历(数组)、求长度(数组)、获取某个属性(对象)等等。
案例:


let exampleArr = [ 1, 2, 3 ];

console.log("数组长度为:", exampleArr.length);

let exampleObj = { "name" :  "myName" };

console.log("对象name属性为:", example.length);

结果: 

数组长度为:3

对象name属性为:myName

这种情况肯定是正常的,那我们不妨思考一下,如果exampleArr 的值不存在呢

那此时的输出肯定是:VM663:1 Uncaught TypeError: Cannot read properties of undefined (reading 'length') at <anonymous>:1:9

那exampleObj不存在呢?结果为:Uncaught TypeError: Cannot read properties of undefined (reading 'myName') at <anonymous>:1:12

可以看到都是不能从undefined 上读取属性 *** ,那我们改成?的语法试试好了

let exampleArr1 = [ 1, 2, 3 ];

console.log("exampleArr1数组长度为:", exampleArr1.length);

let exampleArr2;

console.log("exampleArr2数组长度为:", exampleArr2?.length);

结果:
exampleArr1数组长度为: 3

exampleArr2数组长度为: undefined

结果已经非常明显了,?符号起到了避免错误直接产生的作用,这在开发这中是非常方便的一个功能

符号:??
作用:判断( ?? )前面的内容是否是undefined 或者 null ,如果是,则执行 ( ?? ) 后的内容

适用场景:当赋值、传参等等的内容不存在时,将值替换为 ?? 后的内容。

案例:


let example1 = undefined ?? 123;

let example2 = null ?? 123;

console.log("example1的值为:", example1);

console.log("example2的值为:", example2);

结果:
example1的值为: 123

example2的值为: 123

注意: 如果 ?? 前的值为false,则也会执行符号后面的值

符号:| |
作用:判断( | | )前面的内容是否满足为true ,前满足true则返回前,只有后满足true则返回后,都不满足则返回后

适用场景:只需要满足多个条件的一个就返回满足的值。

案例:


let example1 = undefined || true;

let example2 = true || false;

let example3 = null || false;

console.log("example1的值为:", example1);

console.log("example2的值为:", example2);

console.log("example3的值为:", example3);

结果:
example1的值为: true

example2的值为: true

example3的值为: false

注意: 如果 || 前的值为0,则也会执行符号后面的值

符号:&&
作用:判断( && )两侧的内容是否同时满足,如果是,则返回false

适用场景:当某个值存在时才显示某块内容或同时满足条件后出发某些操作等等。

案例:


let example1 = undefined && true;

let example2 = null && true;

let example3 = true && undefined;

let example4 = true && null;

let example5 = null && false;

console.log("example1的值为:", example1);

console.log("example2的值为:", example2);

console.log("example3的值为:", example3);

console.log("example4的值为:", example4);

console.log("example5的值为:", example5);

结果:
example1的值为: undefined

example2的值为: null

example3的值为: undefined

example4的值为: null

example5的值为: null

注意: 如果 && 前的值满足false,则返回前面的值,如果后面的满足false则返回后面的值,都不满足返回前面的值

好啦,文章到此就结束啦,有问题欢迎评论区讨论,拜拜啦👋

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值