1

I have the following code and need to check if a value exists as an array key.

I can't seem to generate the index of the key even though it does exist, any help would be great.

Code:

var run = { // store the actions to trigger

    block : function() {
        console.log('Blocking…');
    },

    warning : function() {
        console.log('Warning…');
    }

};

console.log( $.inArray( 'warning' , run ) );

As far as I can see, warning exists inside run{} and should return an index of 1.

Why isn't the above doesn't get found (index is returned as -1).

Thanks for reading.

1
  • $.inArray() expects the 2nd parameter to be an actual array. Something like var arr = [1,2,'three', 3.5,4]; Commented Feb 20, 2011 at 8:26

2 Answers 2

6

run isn't an array (it's just a plain object) so it doesn't have an index. Even though block comes before warning, objects are order-less, so you can't say that run has an index of 1.

To check if an object has a particular key, simply check:

if ('warning' in run) {...}

Or:

if (run.warning) {...}
Sign up to request clarification or add additional context in comments.

1 Comment

Doh! Thanks for your help, that makes perfect sense. I should really know by now that {} != []. Either way, thanks again.
1

You can simply use:

console.log(run.warning);

If you get a value, you've found your function.

As for the index - run isn't an array, it is an object (or a hash, or a map, depending on when you're coming from). Objects' properties do not have orders, and they are not even guaranteed to keep the same order every time you iterate over them.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.