2015-11-07 81 views
-1

所以,我想检查我输入的输入是否正确执行,但为什么if语句总是返回false,即使我给出正确的输入? 我不想要解决方案只需要解释。请问有谁能解释?我已经包含了我的html输入元素,以防万一出错。需要这个词的解释guessing javascript

<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

'为什么if语句总是返回FALSE'因为它是一个鬼if语句! –

+0

把完整的代码 –

+0

其余的代码在哪里? – Stefan

回答

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; 
} 
+0

它没有工作,即使输入数组字符串 – Robin

+0

之一,它仍然记录“再试一次”?如果运行'guess(“O”)',它应该在控制台上输出“O”,就像它在最近的Firefox的Scratchpad中和“节点”中一样。如果你给它'猜(“K”)''应该在控制台上打两个“K”,就像它在这里一样,最后如果你运行'guess(“g”)'它应该打印“再试一次”。返回值分别为“true”,“true”和“false”。 – deamentiaemundi