JavaScript 中 if 语句是什么?


if 语句是 JavaScript 中判断并在此基础上执行语句的基本控制语句。 

语法

基本 if 语句的语法如下 -

if(expression){
   Statement(s)to be executed if expression is true
}

在此,将对某个 JavaScript 表达式进行求值。如果结果为 true,则执行给定的语句。如果表达式的值为 false,则不执行任何语句。大部分时候,你在决策时会用到比较运算符。

示例

你可以尝试运行以下内容,了解如何在 JavaScript 中使用 if 语句 -

在线演示

<html>
   <body>
      <script>
         var age = 25;
         if( age > 18 ){
            document.write("Eligible to vote!");
         }
      </script>
      <p>Set the variable to different value and then try...</p>
   </body>
</html>

更新于: 13-6 月-2020

227 人查看

启动你的职业

完成课程即可获得认证

开始学习
广告
© . All rights reserved.