如何检查一个数组的值是否不等于另一个数组的值?

时间:2016-03-26 06:43:04

标签: javascript arrays

我知道,TL; DR - 请耐心等待我。

这个Javascript函数应该接受用户输入的两个字符串(用户名,密码),使用随机函数正确猜测两个字段,以生成存储在两个字符串中的随机字符猜测(输出92个字符)。猜数组,"并且通过比较两组两个数组的值来告诉在同一个实例中猜测你的用户名和密码需要多少次(试验):用户名的猜测数组与用户输入的用户名数组,以及猜测密码的数组与用户输入的密码数组。

我遇到问题的主要代码:

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

通常(没有第二组数组),我会通过嵌套" while循环"来处理这种情况。在" for循环"像这样:

for(x = 0; x< userNameArray.length; x ++){

while(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)]);
            }
    }

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

您可以编写一个辅助函数来检查数组是否相等。有关此功能,请参阅此post

然后你可以说:

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

编辑:
您应该阅读refactoring,这是一种打破将代码重组为更简单,可重用的单元的方法。

重构是我们在这里所做的。检查数组是否相等并不依赖于程序的功能,因此我们可以将其分解为自己的函数。这样可以减少现有函数中的代码,提高可读性,并允许代码的其他部分重用arrayEqual函数。