[英]How to add more than 2 conditions in an If/Else statement in Javascript?
[英]How do I add more than two conditions ?Eg: if , if , else
<!DOCTYPE html>
<html>
<head>
<title>abcd</title>
</head>
<body>
<p id="demo"></p>
<button onclick="vote()">click</button>
<script>
function vote(){
var age,voteable;
age = Number(document.getElementById("age").value);
if (age > 120){
voteable = "not alive";
}
else{
voteable = ( age < 18) ? "Too young" : "Old enough";
}
document.getElementById('demo').innerHTML = voteable;
}
</script>
<input id="age" value="age"/>
</body>
在這里,我只有兩個條件。 如果和其他。如果輸入不是數字,我想添加另一個條件。我該怎么做?
請參閱MDN 文檔:
if (condition1) statement1 else if (condition2) statement2 else if (condition3) statement3 ... else statementN
(當然,您可以用包含多個語句的塊替換任何語句)。
你可以使用else if
<script>
function vote(){
var age,voteable;
age = Number(document.getElementById("age").value);
if (age > 120){
voteable = "not alive";
} else if (age >= 18) {
voteable = "Old enough";
} else {
voteable = "Too young";
}
document.getElementById('demo').innerHTML = voteable;
}
</script>
你可以做
if (age > 120){
voteable = "not alive";
}
else if(age < 0){
voteable = "Not born yet";
}
else {
voteable = ( age < 18) ? "Too young" : "Old enough";
}
以上將與以下內容相同:
if (age > 120) {
voteable = "not alive";
}
else {
if(age < 0) {
voteable = "Not born yet";
}
else {
voteable = ( age < 18) ? "Too young" : "Old enough";
}
}
當您有 2 個以上的條件要檢查時,您可以使用以下方法之一:
if (condition1)
statement1
else if (condition2)
statement2
else if (condition3)
statement3
...
else
statementN
例子
if (x > 50) {
/* do something */
} else if (x > 5) {
/* do something */
} else {
/* do something */
}
或者
switch (expression) {
case value1:
//Statements executed when the
//result of expression matches value1
[break;]
case value2:
//Statements executed when the
//result of expression matches value2
[break;]
...
case valueN:
//Statements executed when the
//result of expression matches valueN
[break;]
[default:
//Statements executed when none of
//the values match the value of the expression
[break;]]
}
例子
switch (expr) {
case 'Oranges':
console.log('Oranges are $0.59 a pound.');
break;
case 'Cherries':
console.log('Cherries are $3.00 a pound.');
break;
case 'Papayas':
console.log('Mangoes and papayas are $2.79 a pound.');
break;
default:
console.log('Sorry, we are out of ' + expr + '.');
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.