javascript条件运算符问题

时间:2017-09-30 15:15:50

标签: javascript

您好抱歉,如果这是一个重复的问题,但我想知道是否有人可以帮我解决我的代码我不知道我错过了什么我应该创建一个用户输入年龄的页面返回票价的结果。

5岁以下的人免费入场 在5至12岁(含)之间,儿童票价为5.00美元 12岁以上的成人票价为9.00美元

这是我的代码:

function myFunction() {
    var age; 
    var older;
    var young;
    
    age = document.getElementById("age").value;
    
    
    older = (age >= 13) ? "$9":"$5";
    
    document.getElementById("demo").innerHTML = older + " movie";
}
<body>

<p>Input your age and click the button:</p>

<input id="age" />

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>
<p> Under age 5 entry is free

Between ages 5 and 12 (inclusive) a childís ticket costs $5.00

Older than 12 an adult ticket costs $9.00 </p>
<body>

2 个答案:

答案 0 :(得分:3)

您可以在条件运算符

的开头添加//Put the content of the file into the editor editor.session.setValue(content); //Restore code folds for(var i = 0; i < folds.length; i++) { editor.session.addFold("...",folds[i]); } //Put the cursor in the correct place editor.focus(); editor.gotoLine(cursor.row,cursor.column, true); editor.renderer.scrollToRow(cursor.row); 的检查

age < 5
function myFunction() {
    var age; 
    var older;
    var young;
    
    age = document.getElementById("age").value;       
    
    older = age < 5 ? "free" : (age >= 13) ? "$9" : "$5";
    
    document.getElementById("demo").innerHTML = older + " movie";
}

答案 1 :(得分:0)

您可以通过链接ifs轻松实现您想要的目标:

function myFunction() {
    var age = document.getElementById("age").value;
    var price;

    if (age >= 13) {
        price = "$9";
    }
    else if (age >= 5) {
        price = "$5";
    }
    else {
        price = "Free";
    }

    document.getElementById("demo").innerHTML = price + " movie";
}

或者,如果你真的,真的想要使用速记:

function myFunction() {
    var age = document.getElementById("age").value;
    var price = (age >= 13) ? "$9" : ((age < 5) ? "Free" : "$5");

    document.getElementById("demo").innerHTML = price + " movie";
}

括号是可选的。我只是将它们包括在内,以明确发生了什么。