0

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
  • Your array is an object when using strings as indicies. Commented Nov 21, 2010 at 18:56

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

Comments

3

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.*

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.