JS& jQuery:如果索引是字符串,则inArray()和indexOf()无法正常工作? [英] JS & jQuery: inArray() and indexOf() are not working properly if indexes are strings?
问题描述
我有一个像这样的数组:
var arr = [];
arr['A string'] = '123';
arr['Another string'] = '456';
我正试图找到索引"123"或"456".
两者:
var string = $.inArray('123', arr)
和
var string = arr.indexOf('123')
给我-1.当索引是字符串时,能否使其正常工作?
问题是您将JavaScript数组用作关联数组,指出了这一点,但我认为很多JavaScript开发人员会坚持使用整数来说明问题.* > I have an array like this: and Im trying to find an index of '123' or '456'. Both: and are giving me -1. Is it possible to get it working when indexes are strings? 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, another would be using the **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.* 这篇关于JS& jQuery:如果索引是字符串,则inArray()和indexOf()无法正常工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!var arr = [];
arr['A string'] = '123';
arr['Another string'] = '456';
var string = $.inArray('123', arr)
var string = arr.indexOf('123')
// I'm guessing that you meant to give numerical and not string values
var arr = [123, 456];
var obj = {
'A string' : 123,
'Another string' : 456
};
'A string'
and 'Another string'
are properties of object obj
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 using hasOwnProperty
if (obj.hasOwnProperty('A string')) {
// if obj has property 'A string' as a direct property
}
in
keywordif ('A string' in obj) {
// if obj has a property 'A string' as a property (could be an inherited property too)
}