JavaScript If-Else错误

JavaScript If-Else错误,javascript,if-statement,Javascript,If Statement,所以我的ifelse结构有一个小问题。当我输入一颗正确的星星,例如“织女星”,配角显示它是错误的(“错误”),而它需要显示我“天琴座” 我的代码如下: var stars=[“北极星”、“奥尔德巴兰星”、“德涅布星”、“织女星”、“牛郎星”、“杜比星”、“轩辕星”]; var共配=[“小熊座”、“金牛座”、“天鹅座”、“天琴座”、“天鹰座”、“大熊座”、“狮子座]; 函数数组(){ 对于(n=0;n

所以我的
if
else
结构有一个小问题。当我输入一颗正确的星星,例如“织女星”,配角显示它是错误的(“错误”),而它需要显示我“天琴座”

我的代码如下:

var stars=[“北极星”、“奥尔德巴兰星”、“德涅布星”、“织女星”、“牛郎星”、“杜比星”、“轩辕星”];
var共配=[“小熊座”、“金牛座”、“天鹅座”、“天琴座”、“天鹰座”、“大熊座”、“狮子座];
函数数组(){
对于(n=0;n<7;++n){
if(test.inputStars.value==stars[n]){
test.inputCostellations.value=共细分[n];
}否则{
test.inputCostellations.value=“Error”;
}
}			
}

阵列结构

问题是,当的
循环运行时,
test.inputConstellations.value
将被覆盖,即使之前程序发现了匹配项。解决方案是
中断

if(test.inputStars.value==stars[n]){
    test.inputConstellations.value=constellations[n]
    break
}else{
    test.inputCostellations.value = "Error"
}
var stars=[“北极星”、“奥尔德巴兰星”、“德涅布星”、“织女星”、“牛郎星”、“杜比星”、“轩辕星”];
var共配=[“小熊座”、“金牛座”、“天鹅座”、“天琴座”、“天鹰座”、“大熊座”、“狮子座];
函数数组(){
对于(n=0;n<7;++n){
if(test.inputStars.value==stars[n]){
test.inputCostellations.value=共细分[n];
打破
}否则{
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() {

    test.inputCostellations.value = "Error"; 
    for (n = 0; n < 7; ++n) {
        if (test.inputStars.value == stars[n]) {
            test.inputCostellations.value = costellations[n];
        }
    }           
}
var stars=[“北极星”、“奥尔德巴兰星”、“德涅布星”、“织女星”、“牛郎星”、“杜比星”、“轩辕星”];
var共配=[“小熊座”、“金牛座”、“天鹅座”、“天琴座”、“天鹰座”、“大熊座”、“狮子座];
函数数组(){
test.inputCostellations.value=“Error”;
对于(n=0;n<7;++n){
if(test.inputStars.value==stars[n]){
test.inputCostellations.value=共细分[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;
        }
    }           
}
var stars=[“北极星”、“奥尔德巴兰星”、“德涅布星”、“织女星”、“牛郎星”、“杜比星”、“轩辕星”];
var共配=[“小熊座”、“金牛座”、“天鹅座”、“天琴座”、“天鹰座”、“大熊座”、“狮子座];
函数数组(){
test.inputCostellations.value=“Error”;
对于(n=0;n<7;++n){
if(test.inputStars.value==stars[n]){
test.inputCostellations.value=共细分[n];
打破
}
}           
}

请将代码带到问题中,以便人们提供帮助。将代码以文本形式发布在问题中。大家好,我很抱歉,我是Stack Overflow的新手,但我会尽力适应环境。我只是在我的问题中发布了代码。@Taplar哇,我不知道。但这似乎不是个好主意。