请选择 进入手机版 | 继续访问电脑版

UBAINS

 找回密码
 立即注册
搜索
热搜: UBAINS
查看: 1876|回复: 0

[学习笔记] JavaScript的短路特性

[复制链接]

10

主题

11

帖子

447

积分

版主

Rank: 7Rank: 7Rank: 7

积分
447
QQ
发表于 2020-10-28 18:52:07 | 显示全部楼层 |阅读模式
JavaScript的短路特性短路
在js逻辑运算中,0、""、null、false、undefined、NaN都会判为false,其他都为true.

对&& 和|| 来说,如果从左边的操作数能够得出结果,就可以忽略右边的操作数。我们将这种现象称为“短路”(即执行最短路径)。

以 a && b 为例,如果 a 是一个假值,足以决定&& 的结果,就没有必要再判断 b 的值。同样对于a || b,如果 a 是一个真值,也足以决定 || 的结果,也就没有必要再判断 b 的值。

"||"实测如下,|| 左边的逻辑运算运算为 时,不管右边值为多少,返回右边的值。

  1. console.log(3 || 3);            //3
  2. console.log(3 || 0);            //3
  3. console.log(0 || 3);            //3
  4. console.log(null || 1);         //1
  5. console.log(null || undefined); //undefined
  6. console.log(0 || undefined);    //undefined
  7. console.log(undefined || 0);    //0
  8. console.log(undefined || 1);    //1
复制代码



可以利用这个特性来给参数赋默认值,下面的函数如果不传参时,设置默认参数;

  1. function getInfo(name, type) {
  2.     varnames = name || "ubains";
  3.     vartypes = type || "EC-8000";
  4.     returnnames + " " + types;
  5. }
  6. getInfo();                  //ubains EC-8000
  7. getInfo("hello");           //hello EC-8000
  8. getInfo("hello","world");   //helloworld
复制代码



逻辑运算符可以多个连接一起使用,所以也可以有多个取值选择,通常利用这个特性来给函数中的参数赋默认值,对于某些参数没传入时赋值默认值。

  1. console.log(9 || undefined || 2); //9
  2. console.log(0 || 3 || 1);         //3
  3. console.log(0 || undefined || 1); //1
  4. console.log(0 || undefined || 0 || 6); //6

  5. //max_width、obj.max_width、name参数不存在时赋默认值
  6. varmax = max_width || obj.max_width || 500 ;
  7. varnames = name || "";
复制代码

"&&"实测如下,|| 左边的逻辑运算运算为 时,不管右边值为多少,返回右边的值。

  1. console.log(null && 1);         //null
  2. console.log(null && true);      //null
  3. console.log("" && true);        //""
  4. console.log(false && true);     //false
  5. console.log(undefined && true); //undefined
  6. console.log(NaN && true);       //NaN
  7. console.log(Object && true);    //true
  8. console.log(Array && true);     //true
  9. console.log(Object && 1);       //1
  10. console.log(Array && 0);        //0
  11. console.log(null && 1);         //null
  12. console.log(1 && undefined);    //undefined
  13. console.log("hello" && 9);      //9

  14. console.log(9 && 6 && undefined); //undefined
  15. console.log(0 && 3 && 1);         //0
  16. console.log(3 && false && 6);     //false
复制代码



总结

js中 || 和 && 的特性帮我们精简了代码的同时,也带来了代码可读性的降低。但是用 || 逻辑或运算可以作为一个固定写法为函数参数赋默认值还是非常好的。


高级模式
B Color Image Link Quote Code Smilies |上传

本版积分规则

Archiver|手机版|小黑屋|BBS.UBAINSYUN.COM

GMT+8, 2024-3-29 22:09 , Processed in 0.035058 second(s), 19 queries .

Powered by UBAINS! X3.4

© 2001-2017 UBAINS Inc.

快速回复 返回顶部 返回列表