2017-08-30 111 views
-3

我嘗試了不同的解決方案,無法找出爲什麼我無法將字符串與數組字符串進行比較。無法將字符串與數組進行比較

這是我曾嘗試:

function checkWin(){ 
 
    let emptyword =["h,","e,","l,","l","o"] 
 
    let computerword= "hello"; 
 
    var a = emptyword.join(""); 
 
    let b = computerword.toString(); 
 
    let c = a.toString(); 
 

 
    console.log("computerword :" + b); 
 
    console.log("emptyword is:" + c); 
 

 
    if(b === c) { 
 
    console.log("someone has won"); 
 
    } else if (b != c) { 
 
    console.log("b is not same as c");      
 
    } 
 
} 
 
checkWin()

我不能去「有人曾榮獲」作爲控制檯打印值超出然而,當條件是不正確的兩個是相同的值,即hellohello

任何支持是最受歡迎的。

+0

'讓C = a.toString();'一已經是一個字符串這樣的toString()也沒有必要有 – epascarello

+0

您的控制檯線應彈出出來,並告訴你錯誤.... – epascarello

+0

我同意你的感謝指出, – Wazzie

回答

3

這是一個錯字。您的陣列是元件

  • 的列表中的 「H」
  • 的 「e,」
  • 「L」
  • 「L」
  • 「○」

的前三個元素包含逗號作爲字符串的一部分。

正確的代碼是:

function checkWin() { 
 
    let emptyword = ["h", "e", "l", "l", "o"] 
 
    let computerword = "hello"; 
 
    var a = emptyword.join(""); 
 
    let b = computerword; 
 

 
    console.log("computerword: " + b); 
 
    console.log("emptyword is: " + a); 
 

 
    if (a === b) { 
 
    console.log("someone has won"); 
 
    } else if (a !== b) { 
 
    console.log("b is not same as c"); 
 
    } 
 

 
} 
 

 
checkWin()

變化

let emptyword = ["h,", "e,", "l,", "l", "o"] 

let emptyword = ["h", "e", "l", "l", "o"] 

修復它。

+0

你的改變XXX行是錯誤的....看起來你是告訴OP,它是間距問題。 – epascarello

+0

我的不好,我手工輸入(出於某種原因),我想我的手指太聰明,我自己的好 –

+0

var a = emptyword.join(「」); – Wazzie

0

我已經通過「Array.match()」解決了我的問題,基本上,如果它找不到匹配項,它將在找到匹配項時返回'null',它將顯示匹配項。

這裏是我解決我的這個難題

function checkWin(){ 

      var a = emptyword.join(""); 
      var b = computerword; 
      var c= b.match(a); 

      // for debug purpose only  
     console.log("match word so far...:"+ c); 

    if(c != null) 
     { 
      console.log("match win"); 
      // clear the previous information 
      document.getElementById("correctguess").innerHTML =" "; 

      document.getElementById("correctguess").innerHTML ="You have Won well done"; 

     } 
     // for debug purpose only 
     console.log("emptyword is:"+ a); 
     console.log("computerword is: "+ b); 


}// end CheckWin 
相關問題