0

I realize that IndexOf will return a -1 when it doesn't find a value within an array, however, the value that I have it searching for is in the array. I have confirmed this by returning the value in the array with console.log

Here is some of my code (paraphrased for simplicity):

var xtiles = [];

function assignValue(tile) {
    xtiles.push(tile); //tile is 1 at this point
    checkArray();
}

function checkArray() {
    var temp = xtiles.indexOf(1);
    console.log(temp); //this returns a -1
    console.log(xtiles[0]); //this returns a 1
}

The variable 'temp' should return a 0 since there is a 1 in index 0 of the array xtiles. What am I missing here?

CdnXxRRODxX
  • 341
  • 5
  • 14

2 Answers2

0

That's because the number 1 is not strictly equal to the string '1'.

indexOf() compares searchElement to elements of the Array using strict equality (the same method used by the ===, or triple-equals, operator).

References:

zerkms
  • 249,484
  • 69
  • 436
  • 539
0

If the content of the array are strings then you can perhaps search as follows:

var temp = xtiles.indexOf(1+""); // force 1 into a string
MervS
  • 5,724
  • 3
  • 23
  • 37