Javascript或比较数组不起作用?

时间:2014-04-16 02:45:44

标签: javascript

var answers = ["hello", "my name is", "how are you?", "what is your name?", "how much does         it cost?"];

var answers2 = ["hi", "my name is", "are you well?", "what's your name?", "how much is     it?"];

$("#submmit").click(function() {
    var totalYes=0;
    function checkAnswers() {
    for(var i=0; i<answers.length; i++) {
        var userAnswer = document.getElementById("b"+i).value;
        if(userAnswer===(answers[i] || answers2[i])) {
            totalYes++;
            $("#correcto").show();
        } else {
            $("#incorrecto").show();
        }
    }
    }
    checkAnswers();
});

当我从answers数组输入正确答案时,程序有效,但不能从答案2输入。当我输入来自answers2的答案时,它显示为&#34;不正确&#34;。请帮忙。

2 个答案:

答案 0 :(得分:5)

它不会检查answers2数组,因为

(answers[i] || answers2[i])

这个表达式首先计算answers[i],这就是Truthy(非空字符串),因此返回。由于||短路,answers2[i]永远不会被评估。

检查此方法的正确方法是使用Array.prototype.indexOf,就像这样

if (answers.indexOf(userAnswer) !== -1 || answers2.indexOf(userAnswer) !== -1) {
    totalYes++;
    $("#correcto").show();
} else {
    $("#incorrecto").show();
}

答案 1 :(得分:-1)

试试这个。我希望这能解决你的问题

if(userAnswer == answers[i] || userAnswer == answers2[i])

尝试替换此行。

JSFiddle