需要解释这个词猜猜javascript

时间:2015-11-07 16:25:45

标签: javascript html

所以,我想检查我给出的输入是否正确执行,但为什么if语句总是返回false,即使我给出了正确的输入? 我不希望解决方案只需要解释。请有人能解释一下吗?我已经包含了我的html输入元素以防它出现问题。

<script>

    var text1 = ["O","K","E"];
    var text2 = ["_","_","_"];

    function guess(j){
        for(i=0; i < text1.length; i++){
            if(j == text1[i]){
                text2[i] = j;
                console.log(text2[i])
            }
            else {
                    console.log("try again")
            }
        }
    }
</script>

1 个答案:

答案 0 :(得分:0)

@Unglückspilz在代码中的评论:

// extra "K" to show how to handle multiple finds
var text1 = ["O","K","E","K"];
var text2 = ["_","_","_","_"];

function guess(j){
    // a flag to set if one or more letters were found
    found = false;
    // check every letter in the haystack against given needle
    for(i=0; i < text1.length; i++){
        if(j == text1[i]){
            // exchange underbar against found letter(s)
            text2[i] = j;
            console.log(text2[i]);
            // set flag to true
            found = true;
        }
    }
    // no letter was correct
    if(!found){
        console.log("try again");
    }
    // return boolean if anything was found (but not how many)
    return found;
}