0

As far as I know jQuery has a function inArrary which is apply like the following

$.inArray(value, array); it return -1 if not in array 

However, this function only apply to value and is not suitable for the multidimension array

eg . fruit [ apple,orange]

For instance, if I have an array like this

eg. fruit [apple => [red,$1], orange => [orange,$5]]

I have to check whether a value exist (eg. banana) as the array key, are there any function appropriate in this case?

1
  • your question/example is not really clear. Are you referring to indexOf() ? Commented Feb 8, 2013 at 2:28

1 Answer 1

1

Arrays cannot have string keys in JavaScript. Only objects can.

If you want to see if an object contains has a key banana, you can simply test that it isn't undefined:

if (myObject.banana != undefined) {

}

... or use hasOwnProperty, which may be better in cases when you may have initialized a property to undefined:

if (myObject.hasOwnProperty("banana")) {

}
Sign up to request clarification or add additional context in comments.

4 Comments

I'd use 'banana' in myObject. Also, I'd use !== undefined, as myObject.banana can be null.
"Arrays cannot have string keys" - but they can have properties since they are still objects :)
really helpful, that's all I want
You should go with hasOwnProperty - not having a property is not the same as that property existing and being undefined.

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.