为什么这段代码不起作用!它始终是默认的,无论我做什么,我没有看到没有人在stackoverflow中遇到类似的问题。请帮忙
var age = 20;
switch(age){
case(age<10):
document.getElementById("box").innerHTML = "you are a kid";
break;
case(age>10 && age<=18 ):
document.getElementById("box").innerHTML = "you are teen";
break;
case(age>18):
document.getElementById("box").innerHTML = "you are adult";
break;
default:
document.getElementById("box").innerHTML = "Some thing is broken!!";
}
&#13;
<html>
<head>
</head>
<body>
<div id="box"></div>
<!--External Javascrip-->
<script type="text/javascript" src="script.js"></script>
</body>
</html>
&#13;
答案 0 :(得分:1)
为age
切换true
。请注意,使用if/else
:
var age = 20;
switch (true) {
case (age < 10):
document.getElementById("box").innerHTML = "you are a kid";
break;
case (age > 10 && age <= 18):
document.getElementById("box").innerHTML = "you are teen";
break;
case (age > 18):
document.getElementById("box").innerHTML = "you are adult";
break;
default:
document.getElementById("box").innerHTML = "Some thing is broken!!";
}
<div id="box"></div>