0

so I'm creating a matching game, here is my click listener:

let clicked = -1;
var values = [];

//on click listener function for squares
var box_clicked = function(box){
box.addEventListener("click", function(){
    clicked = clicked + 1;

    //HERE ARE THE VALUES THAT I WANT TO COMPARE
    var value = this.innerHTML;
    values.push(value);
    if(clicked === 2){
        twoClicked();
    }
    console.log(clicked);
    $(this).addClass("fade z-index");
 });
}

So when clicked equals 2 and the twoClicked() function is called this code runs:

var twoClicked = function(){
    $("div").removeClass("fade z-index");
    clicked = 0;
    var third_value = values.pop(2);
    console.log(values);

    var x = values.indexOf(0);
    var y = values.indexOf(1);
    alert(x);// this alerts -1 for some reason
    alert(y);// this alerts -1

    //if x and y equal then alert "A MATCH"

    values = [];
    values.push(third_value);

}

If I alert x or y it returns -1, why isn't it giving me the value of the two boxes that i clicked.

check out the game here if you want the full code check it out here

2
  • 1
    The .indexOf() method returns the index at which the specified value first appears in the array, or returns -1 if the value isn't in the array. Presumably the values 0 and 1 aren't in the array. If you want to get the value from indices 0 and 1 use values[0] and values[1]. It would be helpful if you could edit the question to show the relevant HTML directly in the question body, so that we can see what values you're pushing. Commented Oct 12, 2017 at 1:34
  • @nnnnnn Thanks for that input! I never knew it returned -1 if there wasn't anything in the array. Commented Oct 12, 2017 at 1:38

1 Answer 1

2

The indexOf function returns the index of the first element where the value is found. It returns -1 if the value is not found in the array.

This code

var x = values.indexOf(0);

...will return the index of the first element that contains 0. if none of the elements is set to 0, it returns -1.

If you want the value of the element at index 0, just use this:

var x = values[0];
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.