1.短路求值(short-circuit evaluation):

- false && anything       // 被短路求值为false ,表达式的anything部分不会被求值
 
 - true || anything        // 被短路求值为true,表达式的anything部分不会被求值
 
 - '你'||'我'||'它'         // 被短路求值为‘你’

 - '你'&&'我'&&'它'         // 被短路求值为‘它’
 
 /* 短路表达式可用来给变量默认赋值,emmmmm...我是这样用的。*/

1.jpg
2.jpg

判断是否登录传统方法

let username = '';
let defaultName;
 
if (username) {
  defaultName = username;
} else {
  defaultName = 'Stranger';
}
 
console.log(defaultName); // Prints: Stranger

用短路求值简化

let username = '';
let defaultName = username || 'Stranger';
 
console.log(defaultName); // Prints: Stranger

Because || or statements check the left-hand condition first, the variable defaultName will be assigned the actual value of username if it is truthy, and it will be assigned the value of 'Stranger' if username is falsy. This concept is also referred to as short-circuit evaluation.

2.三元操作(Ternary Operator):注意return

原程序:

let isNightTime = true;
 
if (isNightTime) {
  console.log('Turn on the lights!');
} else {
  console.log('Turn off the lights!');
}

三元操作简化后程序:

isNightTime ? console.log('Turn on the lights!') : console.log('Turn off the lights!');

注意:如果有return则要写在最前:

原程序

  if (checkA === checkB) {
    return func(val);
  } else {
    return 'inconsistent results';
  }

带return的三元操作简化后程序:

return checkA === checkB ? func(val) : 'inconsistent results';

发表评论