2016-03-25 67 views
1

這是我在這裏的第一篇文章,我有麻煩的措辭問題,所以請忍受我,因爲我一直在這個問題上好幾個小時。Javascript隨機名Guesser:反應遲鈍的腳本問題

我的朋友和我已經想到了一個有趣的小函數,它應該猜測用戶的姓名(通過<input>標籤),在一定的試驗中使用隨機數函數來訪問字母數組0中的字符串-25。該功能也應該爲用戶提供猜測其名稱的試驗次數。

我總是收到一個無響應的腳本(第33行 - 包含第二個「for循環」的行)。

var goal = document.getElementById("your_Name").value; 
var alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]; 
var goalArray = goal.split(""); 
var trials = 0; 
var guessArray = new Array(); 
var i; 
var n; 

for (i = 0; i < goalArray.length; i++){ 
    guessArray.push(alphabet[Math.floor(Math.random()*26)]); 
} 

while (goalArray != guessArray){ 
    trials++; 
    guessArray = []; 
    for (n = 0; n < goalArray.length; n++){ 
    guessArray.push(alphabet[Math.floor(Math.random()*26)]); 
    } 
} 
document.getElementById("appendomatic").innerHTML = "It took " + guessArray + " trials to guess correctly"; 

任何幫助或嘗試幫助將非常感激!

如果有人想知道:我們這個小想法是通過試驗來測試Javascript隨機函數的隨機性(他在MatLab中做了同樣的程序,所以我們將比較兩種語言的隨機函數的結果) 。

+1

'goalArray!= guessArray'總是如此,因爲它們是兩個獨立的數組;即使它們包含相同的元素。 – Paulpro

+0

您需要一個名爲深度比較的東西,幸運的是它不是昂貴的,因爲您的數組沒有非常複雜的結構。有一些圖書館可以幫助解決這個問題,比如'lodash'和'underscore' – woozyking

+0

@woozyking或者因爲它們似乎只是'az'中單個字母的數組,你可以用'goalArray +'來比較它們! = guessArray',因爲數組的'toString()'會正確比較。 – Paulpro

回答

1

goalArray != guessArray始終是真實的,因爲他們是兩個不同的陣列;即使它們包含相同的元素。

由於它們似乎只是a-z中單個字母的數組,因此可以將它們與goalArray + '' != guessArray之類的東西進行比較,因爲數組的toString()將正確比較。

1

這是怎麼了我最終得到它的工作(通過嵌套for循環while循環和第二次在另一個for循環):

var goal = document.getElementById("your_Name").value; 
    var goalArray = goal.split(""); 
    var alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]; 
    var trials = 0; 
    var guessArray = []; 

    for (i = 0; i < goalArray.length; i++){ 
     guessArray.push(alphabet[Math.floor(Math.random()*26)]); 
    } 

    for (x = 0; x < goalArray.length; x++){ 
     while (goalArray[x] != guessArray[x]){ 
      trials++; 
      guessArray = []; 
      for (n = 0; n < goalArray.length; n++){ 
       guessArray.push(alphabet[Math.floor(Math.random()*26)]); 
      } 
     } 
     document.getElementById("appendomatic").innerHTML = "It took " + trials + " trials to guess correctly"; 
    } 
}