问题
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?
回答1:
Like all Array methods and the length
property, the indexOf
method of an Array
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:
function findPropertyWithValue(obj, val) {
for (var i in obj) {
if (obj.hasOwnProperty(i) && obj[i] === val) {
return i;
}
}
return null;
}
var arr = [];
arr['A string'] = '123';
arr['Another string'] = '456';
alert(findPropertyWithValue(arr, "123")); // 'A string'
Note that since all property names, including numeric ones, are converted into strings, you can assign array properties using strings:
var arr = [];
arr["1"] = "foo";
arr[3] = "bar"
arr.indexOf("foo"); // 1
arr.indexOf("bar"); // 3
回答2:
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
// I'm guessing that you meant to give numerical and not string values
var arr = [123, 456];
or use an object
var obj = {
'A string' : 123,
'Another string' : 456
};
Note that using an object, '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
}
another would be using the in
keyword
if ('A string' in obj) {
// if obj has a property 'A string' as a property (could be an inherited property too)
}
**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.*
来源:https://stackoverflow.com/questions/4239621/js-jquery-inarray-and-indexof-are-not-working-properly-if-indexes-are-str