为什么jQuery.inArray不适用于对象数组 [英] Why jQuery.inArray doesn't work on array of objects
本文介绍了为什么jQuery.inArray不适用于对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有对象数组
var arr = [
{"id" : "1", "description" : "one"},
{"id" : "2", "description" : "two"},
{"id" : "3", "description" : "three"}]
我需要获取索引,例如,对于id =2的对象。我做
I need get index, for example, for object with id="2".I do
var index = jQuery.inArray( {"id" : "2", "description" : "two"}, arr )
在索引中我得-1。
推荐答案
因为 inArray
使用 ===
来比较元素,不同的对象永远不会 ===
彼此。 (他们彼此也不是 ==
。)
Because inArray
uses ===
to compare elements, and different objects are never ===
to one another. (They're also not ==
to one another.)
例如:
var a = {"foo": "bar"};
var b = {"foo": "bar"};
console.log(a === b); // "false"
您需要在它们上创建一个方法来比较它们的等价性,然后自己做搜索。
You'll need to create a method on them to compare them for equivalence, and then do the search yourself.
这篇关于为什么jQuery.inArray不适用于对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文