zoukankan      html  css  js  c++  java
  • [译]Javascript中的Ternary operator

    本文翻译youtube上的up主kudvenkat的javascript tutorial播放单

    源地址在此:

    https://www.youtube.com/watch?v=PMsVM7rjupU&list=PL6n9fhu94yhUA99nOsJkKXBqokT3MBK0b

    Ternary operator可以作为if..else..语句的一种简写

    以下是ternary operator的格式

    Boolean语句开头,接着一个?符号,如果Boolean语句为true,则?号后第一个语句运行,如果Boolean语句为false,则:符号后面的那个语句则运行

    以下例子会检查一个数字是为奇数或者偶数.我们用的是if-else语句

    var userInput = Number(prompt("Please enter a number"));
    var message = "";
    if (userInput % 2 == 0) 
    {
        message = "Your number is even";
    }
    else 
    {
        message = "Your number is odd";
    }
    alert(message);

    Ternary operator例子:在以上的例子中if-else语句被ternary operator如下替换

    var userInput = Number(prompt("Please enter a number"));
    var message = userInput % 2 == 0 ? "Your number is even" : "Your number is odd";
    alert(message);

    多个if-else-if语句可以被ternary operator替换

    以下的例子会根据月份的数字来显示月份的名字,该例子由if-else-if语句所写

    var userInput = Number(prompt("Please enter a month number - 1, 2 or 3"));
    var monthName = "";
    
    if (userInput == 1) {
        monthName = "January";
    }
    else if (userInput == 2) {
        monthName = "February";
    }
    else if (userInput == 3) {
        monthName = "March";
    }
    else {
        monthName = "Unknown month number"
    }
    
    alert(monthName);

    ternary operator基于多个条件的例子:在以下的例子中,if-else-if语句会被ternary operator所取代

    var userInput = Number(prompt("Please enter a month number - 1, 2 or 3"));
    var monthName = userInput == 1 ? "January" : userInput == 2 ? "February" : userInput == 3 ? "March" : "Unknown month number";
    alert(monthName);
  • 相关阅读:
    HTML(图像img、表格table、列表)
    HTML(标题h、段落p、文本格式化、链接a、头部head)
    List的复制 (浅拷贝与深拷贝)
    最新CentOS6.5安装Docker, 使用阿里云源下载(亲测)
    VirtualBox安装CentOS6.5
    P1010 幂次方 题解
    P1469 找筷子 题解
    P1866 编号 题解
    EasyNVR通道离线但视频流可正常播放是什么原因导致的?
    EasyNVR通过国标GB28181协议级联出现报错及播放不了的问题调整
  • 原文地址:https://www.cnblogs.com/otakuhan/p/7675262.html
Copyright © 2011-2022 走看看