zoukankan      html  css  js  c++  java
  • JavaScript If…Else 语句

    条件语句用于基于不同的条件来执行不同的动作。


    条件语句

    通常在写代码时,您总是需要为不同的决定来执行不同的动作。您可以在代码中使用条件语句来完成该任务。

    在 JavaScript 中,我们可使用以下条件语句:

    • if 语句 - 只有当指定条件为 true 时,使用该语句来执行代码
    • if...else 语句 - 当条件为 true 时执行代码,当条件为 false 时执行其他代码
    • JavaScript三目运算 - 当条件为true 时执行代码,当条件为 false 时执行其他代码
    • if...else if....else 语句- 使用该语句来选择多个代码块之一来执行
    • switch 语句 - 使用该语句来选择多个代码块之一来执行

    If 语句

    只有当指定条件为 true 时,该语句才会执行代码。

    语法

    if (condition)
      {
     当条件为 true 时执行的代码
      }

    请使用小写的 if。使用大写字母(IF)会生成 JavaScript 错误!

    实例

    当时间小于 20:00 时,生成问候 "Good day":

    if (time<20)
      {
      x="Good day";
      }
    x 的结果是:
    Good day

    尝试一下 »

    请注意,在这个语法中,没有 ..else..。您已经告诉浏览器只有在指定条件为 true 时才执行代码。


    If...else 语句

    请使用 if....else 语句在条件为 true 时执行代码,在条件为 false 时执行其他代码。

    语法

    if (condition)
      {
      当条件为 true 时执行的代码
      }
    else
      {
      当条件不为 true 时执行的代码
      }

    实例

    当时间小于 20:00 时,生成问候 "Good day",否则生成问候 "Good evening"。

    if (time<20)
      {
      x="Good day";
      }
    else
      {
      x="Good evening";
      }

    x 的结果是:

    Good day

    尝试一下 »

    提示:在本站的编程实战中,你可以练习如何使用JavaScript的if语句


    Javascript三目运算(三元运算) 语句

    请使用 (condition1) ? ture-doing : else-doing; 语句在条件为 true 时执行代码,在条件为 false 时执行其他代码。
    实例

    5 > 3 ? alert("5大于3") : alert("5小3");
    

    注意:if...else与三目运算这两者的区别,总结为一句话:三目运算有返回值,if else没有返回值

    例子1:

    var n=1;
    if(n>1){
        n=0;
    }else{
        n++;
    }
    console.log(n);
    #输出结果:2
    
    var n=1;
    n = n>1?0 : n++;
    console.log(n);
    #输出结果为:1
    

    例子2:

    var n=1;
    if(n>1){
        n=0;
    }else{
        ++n;
    }
    console.log(n);
    #输出结果:2
    
    var n=1;
    n = n>1?0 : ++n; 
    console.log(n); 
    #输出结果为:2
    

    If...else if...else 语句

    使用 if....else if...else 语句来选择多个代码块之一来执行。

    语法

    if (condition1)
      {
      当条件 1 为 true 时执行的代码
      }
    else if (condition2)
      {
     当条件 2 为 true 时执行的代码
      }
    else
      {
      当条件 1 和 条件 2 都不为 true 时执行的代码
      }

    实例

    如果时间小于 10:00,则生成问候 "Good morning",如果时间大于 10:00 小于 20:00,则生成问候 "Good day",否则生成问候 "Good evening":

    if (time<10)
      {
      x="Good morning";
      }
    else if (time>=10 && time<20)
      {
      x="Good day";
      }
    else
      {
      x="Good evening";
      }

    x 的结果是:

    Good morning

    尝试一下 »
  • 相关阅读:
    管线命令
    CentOS7搭建本地YUM仓库,并定期同步阿里云源
    linux日志分割脚本
    Centos 7 命令整理
    python实现变脸动画测试
    python打印杨辉三角
    python打印乘法口诀,敏感字替换
    python食人蛇代码
    用python写的考勤自动打卡程序
    tomcat发版脚本
  • 原文地址:https://www.cnblogs.com/navysummer/p/8438892.html
Copyright © 2011-2022 走看看