JavaScript conditional operator (ternary operator)

Ternary operator (ternary operator)

Ternary operator: operator requires three operations

Syntax: Expression 1? Expression 2: Expression 3

1 is a conditional expression, a Boolean value

If the true value of Expression 1, Expression 2 operation is performed, and the results to the expression 2 as a result of the entire expression;

If an expression is false, the operation of Expression 3 is performed, and the result of the expression to 3 as a result of the entire expression;

Example:

'0' and 's' is a boolean true, it returns the value of the second expression 'hello'

Numbers 0 Boolean is false, so the return value of the third expression 'world'

 

 Ternary operator difference with If ... else statements:

Generally ternary conditional expressions if ... else statement has the same effect of expression, the expression of which the former can likewise be expressed;

The biggest difference between the two is that: if ... else statement is no return value, ternary expression returns a value;

Therefore, in case of need to return value can only ternary expression, can not be used if ... else statement;

In the following code, the parameters of the console.log () method must be an expression, the only ternary expressions.

 

 Examples :( nested conditional operator)

Enter a test scores to determine:

If you score 80 or more, excellent output;

If you score 60 or more, the output of qualified;

Otherwise, output: unqualified.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <script>
    var score=85;
    var result=score >= 80? "优秀" : (
        score>=60?""Qualified:"不合格");
    console.log (result);
    </script>
</body>
</html>

Guess you like

Origin www.cnblogs.com/nyw1983/p/11561645.html