[英]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.