2016-03-26 75 views
1

我知道,TL; DR--請耐心等待。如何檢查一個數組的值是否與另一個數組的值不相等?

這個Javascript函數應該包含用戶輸入的兩個字符串(用戶名,密碼),使用隨機函數正確猜測兩個字段以產生存儲在兩個「猜測數組」中的隨機字符猜測,「並且還通過比較兩組兩個數組的值猜測在同一實例中猜測用戶名和密碼的次數(試驗次數):用戶名的猜測數組與用戶名的用戶輸入數組的猜測數組,以及密碼的猜測數組與用戶輸入的密碼數組。

的我在與故障代碼主線:

而(!userNameArray = userNameGuessArray & & passwordArray = passwordGuessArray){

通常(沒有第二組陣列),我將通過嵌套 「while循環」,在處理這種情況是 「for循環」,例如:

爲(X = 0; X < userNameArray.length; X ++){

而(userNameArray [X]!= userNameGuessArray [X]){

唯一的問題是,這一次我需要檢查另一組陣列的除了所述第一組陣列。

我的問題是:

如果未使用「=!」或者用上面的代碼,一個人如何檢查,如果兩個數組有着完全相同的變量?

var username = document.getElementById("your_Username").value; 
var userNameArray = username.split(""); 
var userNameGuessArray = []; 

var password = document.getElementById("your_Password").value; 
var passwordArray = password.split(""); 
var passwordGuessArray = []; 

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","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","0","1","2","3","4","5","6","7","8","9","`","~","!","@","#","$","%","^","&", 
"*","(",")","[","]","{","}","_","-","|","\\","'",'"',",",".",":",";","<",">","/","?"]; 

var trials = 0; 



    while (userNameArray != userNameGuessArray && passwordArray != passwordGuessArray){ 
     trials++; 
     userNameGuessArray = []; 
     passwordGuessArray = []; 
      for (z = 0; z < userNameArray.length; z++){ 
       userNameGuessArray.push(alphabet[Math.floor(Math.random()*92)]); 
      } 
      for (y = 0; y < passwordArray.length; y++){ 
       passwordGuessArray.push(alphabet[Math.floor(Math.random()*92)]); 
      } 
    } 

任何幫助將不勝感激!

+0

因此,你基本上試圖挑選隨機字母,直到它猜到密碼? –

+0

您是否在生成猜測數組的同時繼續生成猜測以匹配用戶的輸入? – gurvinder372

+0

是的,我希望函數能夠在同一個實例中猜測用戶名和密碼,所以在92個字符的字母表中,平均需要92 * 92次嘗試猜測單個字符用戶名和單個字符密碼的輸入。我已經有了一個能夠成功地從單個標記中猜測用戶輸入的函數。對於一個字符串,例如「a」,平均需要92次嘗試/猜測。我會嘗試解決方案'sdsmith'離開我,讓你們知道明天會如何。還有,'gurvinder372',它用push()清除和重新填充數組。 – Mangofett

回答

1

你可以編寫一個輔助函數來檢查數組是否相等。看到這個post這樣的功能。

然後你就可以說:

while(!arrayEqual(arr1, arr2) && !arrayEqual(arr3, arr4)) 

編輯:
您應該refactoring閱讀起來,這是重組代碼爲簡單的,可重複使用的,單位的突破的方法。

重構就是我們在這裏所做的。檢查數組是否相等不取決於程序的功能,所以我們可以將它分解成它自己的函數。這會減少現有函數中的代碼,提高可讀性,並允許代碼的其他部分重用arrayEqual函數。

+0

將嘗試這個並回復給你。謝謝你的投入! – Mangofett

+0

這是否適合您? – sdsmith

+0

我相信如此,而且我正處於突破的邊緣。輔助函數是否必須放在主函數的外部和上方,在while循環之後的主函數中,還是放在任何特殊的地方?回覆此消息後,我會修改主帖。 – Mangofett

相關問題