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

});

为什么不console.log($.inArray(_photoId, photoIds));回来1

4

3 回答 3

3

它似乎_photoId是一个数字,但photoIds包含字符串。试试这个:

$.inArray(''+ _photoId, photoIds)
于 2012-09-15T09:31:59.873 回答
3

我可以想象的字符串与整数。不同的类型意味着 inArray 不会将它们视为相同的。确保您使用的是字符串而不是整数,这应该可以工作。

于 2012-09-15T09:32:00.833 回答
1

这是因为该$.inArray函数还考虑了类型。它不会说整数与字符串相同。这也在文档的第一条评论中进行了解释。

您可以使用_photoId.toString()来获取值的字符串表示形式。

另请注意,ECMAScript (Javascript) 有一个名为indexOf的本机函数,它的作用与 jQuery 完全相同:

photoIds.indexOf(_photoId.toString())
于 2012-09-15T09:34:32.037 回答