-2

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

4

2 回答 2

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>

于 2018-11-30T22:07:29.047 回答
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;
        }
    }           
}
于 2019-01-29T18:10:03.140 回答