Why jQuery.inArray doesn't work on array of objects

前端 未结 3 1369
感动是毒
感动是毒 2021-01-19 02:43

I have array of objects

var arr = [
        {\"id\" : \"1\", \"description\" : \"one\"},
        {\"id\" : \"2\", \"description\" : \"two\"},
        {\"id\"         


        
3条回答
  •  借酒劲吻你
    2021-01-19 03:12

    As TJ said, inArray uses === (indexOf actually, but that's the same thing), therefore even identical literals are compared non equal. Here's a workaround:

    var index = jQuery.inArray( 
        JSON.stringify({"id" : "2", "description" : "two"}), 
        $.map(arr, JSON.stringify) )
    

    http://jsfiddle.net/7kg9P/1/

提交回复
热议问题