所以我的if
else
结构有这个小问题。当我输入正确的星星(例如“ Vega”)时,星罗棋盘向我显示它是错误的(“错误”),而它需要向我显示“天琴座”。
我的代码如下:
var stars = ["Polaris", "Aldebaran", "Deneb", "Vega", "Altair", "Dubhe", "Regulus"];
var costellations = ["Ursu Minor", "Taurus", "Cygnus", "Lyra", "Aquila", "Ursa Major","Leo"];
function Arrays() {
for (n = 0; n < 7; ++n) {
if (test.inputStars.value == stars[n]) {
test.inputCostellations.value = costellations[n];
}else{
test.inputCostellations.value = "Error";
}
}
}
<!DOCTYPE html>
<html>
<head>
<title> Array structures</title>
</head>
<body>
<form name = "test">
<input type = "text" name = "inputStars">
<input type = "button" onclick ="Arrays()" value = "Find costellation">
<input type = "text" name = "inputCostellations">
</form>
</body>
</html>
答案 0 :(得分:4)
问题是,当for
循环正在运行时,test.inputConstellations.value
将被覆盖,即使以前程序找到了匹配项也是如此。解决方案是break
:
if(test.inputStars.value==stars[n]){
test.inputConstellations.value=constellations[n]
break
}else{
test.inputCostellations.value = "Error"
}
var stars = ["Polaris", "Aldebaran", "Deneb", "Vega", "Altair", "Dubhe", "Regulus"];
var costellations = ["Ursu Minor", "Taurus", "Cygnus", "Lyra", "Aquila", "Ursa Major","Leo"];
function Arrays() {
for (n = 0; n < 7; ++n) {
if (test.inputStars.value == stars[n]) {
test.inputCostellations.value = costellations[n];
break
}else{
test.inputCostellations.value = "Error";
}
}
}
<!DOCTYPE html>
<html>
<head>
<title> Array structures</title>
</head>
<body>
<form name = "test">
<input type = "text" name = "inputStars">
<input type = "button" onclick ="Arrays()" value = "Find costellation">
<input type = "text" name = "inputCostellations">
</form>
</body>
</html>
答案 1 :(得分:1)
您可以设置变量的默认值,并在设置为true时覆盖:
var stars = ["Polaris", "Aldebaran", "Deneb", "Vega", "Altair", "Dubhe", "Regulus"];
var costellations = ["Ursu Minor", "Taurus", "Cygnus", "Lyra", "Aquila", "Ursa Major","Leo"];
function Arrays() {
test.inputCostellations.value = "Error";
for (n = 0; n < 7; ++n) {
if (test.inputStars.value == stars[n]) {
test.inputCostellations.value = costellations[n];
}
}
}
休息一下
var stars = ["Polaris", "Aldebaran", "Deneb", "Vega", "Altair", "Dubhe", "Regulus"];
var costellations = ["Ursu Minor", "Taurus", "Cygnus", "Lyra", "Aquila", "Ursa Major","Leo"];
function Arrays() {
test.inputCostellations.value = "Error";
for (n = 0; n < 7; ++n) {
if (test.inputStars.value == stars[n]) {
test.inputCostellations.value = costellations[n];
break;
}
}
}