JS& jQuery:如果索引是字符串,inArray() 和 indexOf() 无法正常工作?
我有一个像这样的数组:
var arr = [];
arr['A string'] = '123';
arr['Another string'] = '456';
我试图找到“123”或“456”的索引。
两者:
var string = $.inArray('123', arr)
并且
var string = arr.indexOf('123')
都给我-1。当索引是字符串时是否可以使其工作?
I have an array like this:
var arr = [];
arr['A string'] = '123';
arr['Another string'] = '456';
and Im trying to find an index of '123' or '456'.
Both:
var string = $.inArray('123', arr)
and
var string = arr.indexOf('123')
are giving me -1. Is it possible to get it working when indexes are strings?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
与所有 Array 方法和
length
属性一样,Array
对象的indexOf
方法仅考虑 Array 的数字属性。这些属性的名称是无符号整数。要测试具有特定值的属性是否存在,您可以对任何对象(包括数组)执行类似的操作。无法保证属性名称的枚举顺序,因此如果有多个具有特定值的属性,那么您无法确定将获得哪个属性:请注意,因为所有属性名称(包括数字属性名称)都会转换为字符串,您可以使用字符串分配数组属性:
Like all Array methods and the
length
property, theindexOf
method of anArray
object only considers numeric properties of the Array. These are properties whose names are unsigned integers. To test for the existence of a property with a particular value, you can do something like this on any object, including arrays. There's no guarantee about the enumeration order of property names, so if there's more than one property with a particular value then you can't be sure which property you'll get:Note that since all property names, including numeric ones, are converted into strings, you can assign array properties using strings:
问题是您使用 JavaScript 数组作为关联数组,
,也可以使用对象。
请注意,使用对象时,
'A string'
和'Another string'
是对象obj< 的属性。 /code> 并且不能像数组中的值一样进行索引。您可以通过多种方式检查对象是否具有属性,其中一种是使用
hasOwnProperty
另一种是使用
in
关键字**除非字符串是字符串32 位无符号整数的表示形式为 Tim 指出,但我认为可以公平地说,为了清晰起见,很多 JavaScript 开发人员会说坚持使用整数。*
The problem is that you are using a JavaScript array as an associative array, something that it is not. The indices of a JavaScript array are unsigned 32 bit integers and therefore you can't use *strings**. You would either use an array like so
or use an object
Note that using an object,
'A string'
and'Another string'
are properties of objectobj
and can't be indexed like the values in an array. You can check that an object has a property a number of ways, one of which would be usinghasOwnProperty
another would be using the
in
keyword**unless the string is the string representation of a 32 bit unsigned integer as Tim points out, but I think it's fair to say that a lot of JavaScript developers would say stick to using integers for clarity.*