Reputation: 1870
I am having an issue where jQuery.InArray()
is returning -1 when I run a function, but I know that the values that I'm testing for are definitely in the array.
I know that they are in the array because if I console.log the values of the array right before I run jQuery.inArray()
the values exist and display. Here is an example of what I'm working with:
/* -- In page.php -- */
images = [8, 13, 21, 32, 40, 56];
/* -- In script.js -- */
console.log('images->', images);
//output images-> [8, 13, 21, 32, 40, 56]
var testingValue = 13;
console.log('inArray->', jQuery.inArray(testingValue, images)); //Should return 1
//output inArray-> -1
console.log('inArray->', jQuery.inArray(13, images)); //Should return 1
//output inArray-> -1
console.log('inArray->', jQuery.inArray("13", images)); //Should return -1
//output inArray-> -1
console.log('inArray->', jQuery.inArray('13', images)); //Should return -1
//output inArray-> -1
All of these return -1
even though the top two should return 1
. The weird thing is that if I manually test for jQuery.inArray(testingValue, images)
in the console, I do get the value 1.
One thing to note: The variable images
is created in the php page that the js file is included in. This shouldn't be an issue.
Additional note: Yes, jQuery is included well before this part of the script runs. Many other jQuery functions are running successfully before this one.
What I am wondering is if there are any gotchas to this function. I have used it successfully in the past and can't see anything with my code which would prevent this from returning a proper value.
Upvotes: 3
Views: 1706
Reputation: 1870
After a good nights rest I was able to circle up and take a fresh look at the problem. The variable testingValue = 13;
is explicitly cast as an integer. The problem was that I was getting that value dynamically through the jQuery $.each(arrayName, function(index,value){})
. Although the data showed that index
was indeed an integer, for some reason $.inArray()
was not treating it like an int/float and therefore was not finding a value in the numeric array. I modified my code to parseInt()
the index
variable before checking that it was inArray.
If you are having trouble trying to use jQuery.inArray() with an array of integers or floats, try using parseInt()
or parseFloat()
, respectively, to ensure that the function is receiving the correct data type.
if( jQuery.inArray(parseInt(yourVariable), yourArray) > -1)
{
return true;
}
Upvotes: 7