JavaScript如果其他错误

时间:2018-11-30 21:55:46

标签: javascript if-statement

所以我的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>

2 个答案:

答案 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;
        }
    }           
}