0
点赞
收藏
分享

微信扫一扫

JS-三元表达式

学习网址:https://www.jstips.co/en/javascript/what-is-the-javascript-ternary-operator/

学习网址:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Conditional_Operator

什么是 JavaScript 三元运算符?

三元运算符是 if 语句的快捷方式。它由三个操作数组成;问号、条件和要执行的表达式(如果条件为 true),后跟冒号和另一个表达式(如果为 false)。

条件(三元)运算符是 JavaScript 唯一使用三个操作数的运算符:一个条件后跟一个问号(?),如果条件为真值,则执行冒号(:)前的表达式;若条件为假值,则执行最后的表达式。该运算符经常当作 if...else 语句的简捷形式来使用。

JS-三元表达式_条件链

第一个示例

let age = 26;
// condition ? expression if true : expression if false 
// 条件表达式 ?   表达式如果为真    : 表达式如果为假
let drink = (age >= 21) ? "Beer" : "Juice"; 
console.log(drink); // "Beer"

// Equivalent to: 等同于:
let drink;
if ((age >= 21)) {
    drink = "Beer";
} else {
    drink = "Juice";
}
console.log(drink); // "Beer"

第二个示例

function getFee(isMember) {
  return isMember ? '$2.00' : '$10.00';
}

console.log(getFee(true));
// Expected output: "$2.00"

console.log(getFee(false));
// Expected output: "$10.00"

console.log(getFee(null));
// Expected output: "$10.00"

> "$2.00"
> "$10.00"
> "$10.00"

语法和参数

condition ? exprIfTrue : exprIfFalse

参数:

condition

计算结果用作条件的表达式。

exprIfTrue

如果 condition 的计算结果为真值(等于或可以转换为 true 的值),则执行该表达式。

exprIfFalse

如果 condition 为假值(等于或可以转换为 false 的值)时执行的表达式。

注意:

除了 false,可能的假值表达式还有:nullNaN0、空字符串("")和 undefined。如果 condition 是其中任何一个,那么条件表达式的结果就是 exprIfFalse 表达式执行的结果。

条件链

三元运算符是右结合的,这意味着它可以按以下方式“链接”起来,类似于 if … else if … else if … else 链:

function example() {
  return condition1
    ? value1
    : condition2
      ? value2
      : condition3
        ? value3
        : value4;
}

等价于以下 [if...else] 链。

function example() {
  if (condition1) {
    return value1;
  } else if (condition2) {
    return value2;
  } else if (condition3) {
    return value3;
  } else {
    return value4;
  }
}

举报

相关推荐

0 条评论