JavaScript-三目运算符

什么是三目运算符

三目运算符又称之为条件运算符。

三目运算符的格式

条件表达式 ? 结果A : 结果B;

在三目运算符中当条件为真的时候, 就会返回结果A。
在三目运算符中当条件为假的时候, 就会返回结果B。

三目运算符的注意点

在三目运算符中 ?: 不能单独出现, 要么一起出现, 要么一起不出现。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Demo</title>
    <script>
        let res = true ? 123 : 456;
        console.log(res);
    </script>
</head>
<body>

</body>
</html>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Demo</title>
    <script>
        let res = false ? 123 : 456;
        console.log(res);
    </script>
</head>
<body>

</body>
</html>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Demo</title>
    <script>
        let res = (10 > 5) ? 10 : 5;
        console.log(res);
    </script>
</head>
<body>

</body>
</html>

posted @ 2021-05-19 17:14  BNTang  阅读(790)  评论(0编辑  收藏  举报