loading

JS - &&、||

简单运用

逻辑且(&&):左右必须都满足 true 才返回 true;

逻辑或(||):左右其中一个满足 true 就返回 true。

let user = localStorage.getItem("user");

if (user && user.age > 10) {
  // ...
}

if 内的条件:当 user 存在时,即true;且 user 的 age 字段大于 10。

进阶运用

逻辑且

左边结果 右边结果 最终执行
true true
false true
true false
false false
function fun(callback) {
  // ...
  callback && callback();
}

fun(() => console.log("execute callback function.")); // 控制台打印了字符串!
fun(); // 什么也没有发生!

逻辑或

左边结果 右边结果 最终执行
true true
false true
true false
false false
function fun(x) {
  x = x || "default value";
}

fun(undefined); // "default value"
fun("inject a value"); // inject a value

使用场景

默认值

function fun(x) {
  x = x || "default value";
}

fun(undefined); // "default value"
fun("inject a value"); // inject a value

当 x 传入的是一个真值时,也就是传递了参数,x 得到的是它本身,而不是后面的默认值。当 x 传入的是一个假值时,也就是没有传递参数,给 x 返回一个默认值。

setTitle(options.title || 'untitled');

在给函数传递参数时,如果 options.title 是 null 或者其他之类的假值,就提供字符串untitled给函数。

函数结果默认值

function countOccurrences(regex, str) {
  return (str.match(regex) || []).length;
}

match()方法会返回一个数组或 null。得益于逻辑或(||),在后一种请看下可以设置一个默认值。因此,在这两种情况下你都可以安全地访问 length 属性。

posted @ 2022-09-04 22:42  Himmelbleu  阅读(326)  评论(0编辑  收藏  举报