Xerunix
Xerunix

Reputation: 431

Javascript arrays returning equal as long as first element is equal

I am trying to compare two javascript arrays of integers up to the length of one array. Meaning, that I have one array that builds with user input and a goal array the user is trying to reach, and I just want to make sure the user has input the correct sequence up to the point that the user has input.

e.g.

If the goal array is [0, 3, 5, 4] and the user has input [0, 3, 5] so far I want my method to return true. My attempt in doing this is:

function compareArrays(){
    for(var i=0; i<playerPattern.length; i++){
        if (playerPattern[i] !== pattern[i]){
            return false;
        } else {
            return true;
        }
    }
}

this is called everytime the event handler picks up user input:

    if(isInButton(greenButton, mouseX, mouseY)){
        playerPattern[playerPattern.length] = 0;
        console.log(pattern);
        console.log(playerPattern);
        console.log(compareArrays());
        if(compareArrays() === false){
            youLose();
        } else if(compareArrays() === true && playerPattern.length === pattern.length){
            clickTile(0);
            score++;
            playerPattern.length = 0; //reset the playerPattern array because they completed the turn
            setTimeout(increasePattern, 1000);
        } else {
            clickTile(0);
        }
    } else if(isInButton(redButton, mouseX, mouseY)){
 ...
 ...

I don't see why this method would return true as long as the first element in the user array is true.

e.g. The method returns true in the case of goal: [0, 3, 4, 5] and user [0, 2, 1, 0]

Upvotes: 0

Views: 33

Answers (1)

NPE
NPE

Reputation: 500307

Given that you have return statements in both branches of the if, your function always stops immediately after comparing the first elements.

The return true statement should be outside the loop:

function compareArrays(){
    for(var i=0; i<playerPattern.length; i++){
        if (playerPattern[i] !== pattern[i]){
            return false;
        }
    }
    return true;
}

Upvotes: 2

Related Questions