|
JavaScript的短路特性短路
在js逻辑运算中,0、""、null、false、undefined、NaN都会判为false,其他都为true.
对&& 和|| 来说,如果从左边的操作数能够得出结果,就可以忽略右边的操作数。我们将这种现象称为“短路”(即执行最短路径)。
以 a && b 为例,如果 a 是一个假值,足以决定&& 的结果,就没有必要再判断 b 的值。同样对于a || b,如果 a 是一个真值,也足以决定 || 的结果,也就没有必要再判断 b 的值。
"||"实测如下,|| 左边的逻辑运算运算为 假 时,不管右边值为多少,返回右边的值。
- console.log(3 || 3); //3
- console.log(3 || 0); //3
- console.log(0 || 3); //3
- console.log(null || 1); //1
- console.log(null || undefined); //undefined
- console.log(0 || undefined); //undefined
- console.log(undefined || 0); //0
- console.log(undefined || 1); //1
复制代码
可以利用这个特性来给参数赋默认值,下面的函数如果不传参时,设置默认参数;
- function getInfo(name, type) {
- varnames = name || "ubains";
- vartypes = type || "EC-8000";
- returnnames + " " + types;
- }
- getInfo(); //ubains EC-8000
- getInfo("hello"); //hello EC-8000
- getInfo("hello","world"); //helloworld
复制代码
逻辑运算符可以多个连接一起使用,所以也可以有多个取值选择,通常利用这个特性来给函数中的参数赋默认值,对于某些参数没传入时赋值默认值。
- console.log(9 || undefined || 2); //9
- console.log(0 || 3 || 1); //3
- console.log(0 || undefined || 1); //1
- console.log(0 || undefined || 0 || 6); //6
- //max_width、obj.max_width、name参数不存在时赋默认值
- varmax = max_width || obj.max_width || 500 ;
- varnames = name || "";
复制代码
"&&"实测如下,|| 左边的逻辑运算运算为 真 时,不管右边值为多少,返回右边的值。
- console.log(null && 1); //null
- console.log(null && true); //null
- console.log("" && true); //""
- console.log(false && true); //false
- console.log(undefined && true); //undefined
- console.log(NaN && true); //NaN
- console.log(Object && true); //true
- console.log(Array && true); //true
- console.log(Object && 1); //1
- console.log(Array && 0); //0
- console.log(null && 1); //null
- console.log(1 && undefined); //undefined
- console.log("hello" && 9); //9
- console.log(9 && 6 && undefined); //undefined
- console.log(0 && 3 && 1); //0
- console.log(3 && false && 6); //false
复制代码
总结
js中 || 和 && 的特性帮我们精简了代码的同时,也带来了代码可读性的降低。但是用 || 逻辑或运算可以作为一个固定写法为函数参数赋默认值还是非常好的。
|
|