2015-11-07 39 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