Johan
Johan

Reputation: 35194

inArray() returns -1 even though element exists in array

$.post('service.php?getPhotos', function(data){ 

    var photoIds = [];

    $.each(data, function(){
        photoIds.push(this.id);
    });

    console.log(_photoId); //7962669392
    console.log(photoIds); //["7980686507", "7962669392", "7962163506"]
    console.log($.inArray(_photoId, photoIds)); //-1

});

Why doesnt console.log($.inArray(_photoId, photoIds)); return 1?

Upvotes: 0

Views: 74

Answers (3)

Emil Vikström
Emil Vikström

Reputation: 91942

This is because the $.inArray function also takes the type into account. It will not say that an integer is the same as a string. This is also explained in the first comment in the documentation.

You can use _photoId.toString() to get the string representation of the value.

Also note that ECMAScript (Javascript) have a native function called indexOf which does exactly the same thing as the jQuery one:

photoIds.indexOf(_photoId.toString())

Upvotes: 1

CodePB
CodePB

Reputation: 1756

string vs integer I would imagine. Different types would mean that inArray does not see them as the same. Make sure you are using a string instead of an integer and this should work.

Upvotes: 3

elclanrs
elclanrs

Reputation: 94101

It seems like _photoId is a number but photoIds contains strings. Try this:

$.inArray(''+ _photoId, photoIds)

Upvotes: 3

Related Questions