jQuery inArray is always returning -1

后端 未结 6 920
遥遥无期
遥遥无期 2020-12-09 09:40

I cannot figure out why I keep getting -1 for lastProductIndex when clearly the lastProductID is in the array!

var lastProductID = 6758;
var allProductIDs =          


        
相关标签:
6条回答
  • 2020-12-09 09:54

    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 matches value, $.inArray() returns 0.

    According to: http://api.jquery.com/jQuery.inArray/

    0 讨论(0)
  • 2020-12-09 09:55

    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);
    
    0 讨论(0)
  • 2020-12-09 10:03

    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.

    0 讨论(0)
  • 2020-12-09 10:07

    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 :)

    0 讨论(0)
  • 2020-12-09 10:11

    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...

    0 讨论(0)
  • 2020-12-09 10:11

    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.

    0 讨论(0)
提交回复
热议问题