Javascript 简明教程

JavaScript - Conditional Operators

JavaScript Conditional Operators

JavaScript 中的 conditional 运算符首先针对真或假值计算表达式,然后根据计算结果执行给定的两个语句之一。条件运算符也称为 ternary 运算符。

The conditional operator in JavaScript first evaluates an expression for a true or false value and then executes one of the two given statements depending upon the result of the evaluation. The conditional operator is also known as the ternary operator.

JavaScript 条件 (三元) 运算符是唯一采用三个操作数的运算符 - 一个条件,后跟一个问号 (?),然后是一个在条件为真时执行的第一个表达式,后跟一个冒号 (:),最后是一个在条件为假时执行的第二个表达式。

The JavaScript conditional (ternary) operator is only operator that takes three operands – a condition followed by a question mark (?), then the first expression to be executed if the condition is truthy followed by a colon (:), and finally the second expression to be executed if the condition is falsy.

JavaScript 中有六个假值。它们分别是 - 0(零)、false、空字符串('' 或 "")、null、undefined 和 NaN。在 JavaScript 中,所有其他值都视为真。

There are six falsy values in JavaScript. These are − 0 (zero), false, empty string ('' or ""), null, undefined, and NaN. All other values are treated as truthy in JavaScript.

Syntax

以下是 JavaScript 中条件 (三元) 运算符的语法 -

Following is the syntax of conditional (ternary) operator in JavaScript −

var variable = condition ? exp1 : exp2;

Parameters

在此处,我们在上述语句中说明了参数。

Here, we have explained the parameters in the above statement.

  1. condition − It is a conditional statement.

  2. exp1 − If the conditional statement evaluates truthy, control flow executes the exp1 expression.

  3. exp2 − If the conditional statement evaluates falsy, control flow executes the exp2 expression.

如果条件的值是任何假值,表达式的结果将是 exp2 的值;否则,它将是 exp1 的值。

If the value of the condition is any falsy value, the result of the expression will be the value of exp2; otherwise, it will be the value of exp1.

Example

在下面的示例中,我们在条件语句中比较 num1 和 num2 变量的值。此处,条件语句计算为真,因此 result 变量包含第一个表达式的值。

In the example below, we compare the value of the num1 and num2 variables in the conditional statement. Here, the conditional statement evaluates true, so the result variable contains the value of the first expression.

<html>
<body>
<div id="output"></div>
<script>
   var num1 = 90;
   var num2 = 67;
   var res = num1 > num2 ? "num1 is greater than num2" : "num2 is greater than num1";
   document.getElementById("output").innerHTML = res;
</script>
</body>
</html>

它将产生以下结果 −

It will produce the following result −

num1 is greater than num2

Example

在下面的示例中,我们根据条件语句的结果向对象属性分配值。

In the example below, we assign the value to the object property according to the conditional statement’s result.

现在,想象一下,如果你需要编写 if-else 语句来有条件地向每个属性分配值。代码将变得复杂,但使用三元运算符,你可以轻松地用一行代码完成。

Now, imagine what if you need to write the if-else statement to assign value to each property conditionally. The code will become complex, but with the ternary operator, you can easily do it with a single line of code.

<html>
<body>
<div id="output"></div>
<script>
   const year = 2004;
   const obj = {
	  name: "John",
	  age: year < 2005 ? "adult" : "minor",
	  city: "New York"
   };

   document.getElementById("output").innerHTML =
   obj.name + " is " + obj.age + " and lives in " + obj.city;
</script>
</body>
</html>

它将产生以下结果 −

It will produce the following result −

John is adult and lives in New York

Example

此示例表明,你还可以使用表达式而不是值。根据条件语句,控制流计算第一个或第二个表达式并将结果值分配给 'result' 变量。

This example demonstrates that you can also use the expression instead of values. According to the conditional statement, control flow evaluates the first or second expression and assigns the resultant value to the 'result' variable.

<html>
<body>
<div id="output"></div>
<script>
   let operator = '-';
   let res = operator == '+' ? 10 + 20 : 10 - 20;
   document.getElementById("output").innerHTML = "The result is: " + res;
</script>
</body>
</html>

它将产生以下结果 −

It will produce the following result −

The result is: -10

简而言之,你可以使用三元或条件运算符来缩短代码,从而使用 if-else 语句。

In short, you can use the ternary or conditional operator to shorten the code, which uses the if-else statement.

Handling null values

我们可以使用 JavaScript 三元表达式来处理空值,如果用户传递了一个空值,它可以设置一个默认值。

We can use the JavaScript conational operator to handle null value to set a default value if the user passes a null value.

Example

尝试以下示例:

Try the following example −

<html>
<body>
<div id="output"></div>
<script>
   const greet = (user) => {
      const name = user? user.name : "stranger";
      return `Hello, ${name}`;
   };
   document.getElementById("output").innerHTML =
   greet({ name: "John" }) + "<br>" +
   greet(null);
</script>
</body>
</html>

它将产生以下结果 −

It will produce the following result −

Hello, John
Hello, stranger