I cannot figure out why I keep getting -1 for lastProductIndex when clearly the lastProductID is in the array!
var lastProductID = 6758;
var allProductIDs =
The
$.inArray()
method is similar to JavaScript's native.indexOf()
method in that it returns -1 when it doesn't find a match. If the first element within the array matchesvalue
,$.inArray()
returns 0.
According to: http://api.jquery.com/jQuery.inArray/
Are you using any other JavaScript libraries in your page?
There could be a conflict for the $
shorthand if you are. This can be solved in a number of ways, one of which would be wrapping the code in a self-executing anonymous function
(function($) {
var lastProductIndex = $.inArray(lastProductID, allProductIDs);
})(jQuery);
Try this instead:
$.grep(allProductIDs, function(n) { return n == lastProductID; });
Caveat: grep returns an array.
It looks like jQuery does an === instead of == with inArray.
This confused me too at first, I had an identical problem. It seems jQuery.inArray() requires a string. So you could just do:
var lastProductID = "6758";
In my case I was trying to do:
var foo = date.getTime()/1000;
Which always resulted in -1 being returned from $.inArray()
But you can just cast it to a string:
var foo = String(date.getTime()/1000);
Hope that helps somebody :)
I had the same problem yesterday,,
var data=[2,4,6,8];
alert( $.inArray(4,data) ) // output 1 as expected
alert( $.inArray("4",data) ) // output -1 as expected
Generally this occurs when you get the value to check from a input element or something that returns a string. You need to do parseInt(string,radix)
to convert it to a number...
Here is why everyone hates languages that are not TYPED. I had initially set the lastProductIndex value with a value, but it was a string (because I had gotten the value from an HttpResponse object from returned JSON. So consequently I had set the variable to a string because of the returned JSON value was a string. When I hard coded the number 6758 into $.inArray it worked fine so that caught my attention.