31

Possible Duplicate:
Checking if an associative array key exists in Javascript

I have a PHP code block . For a purpose I am converting this to a JavaScript block.

I have PHP

if(array_key_exists($val['preferenceIDTmp'], $selected_pref_array[1]))

now I want to do this in jQuery. Is there any built in function to do this?

3

3 Answers 3

16

Note that objects (with named properties) and associative arrays are the same thing in javascript.

You can use hasOwnProperty to check if an object contains a given property:

o = new Object();  
o.prop = 'exists'; // or o['prop'] = 'exists', this is equivalent 

function changeO() {  
  o.newprop = o.prop;  
  delete o.prop;  
}  

o.hasOwnProperty('prop');   //returns true  
changeO();  
o.hasOwnProperty('prop');   //returns false  

Alternatively, you can use:

if (prop in object)

The subtle difference is that the latter checks the prototype chain.

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

1 Comment

The question is bout traditional arrays also, it work for Array()?
6

In Javascript....

if(nameofarray['preferenceIDTmp'] != undefined) {
    // It exists
} else {
    // Does not exist
}

1 Comment

You want to check for undefined with === or !== otherwise you'll get false positives for null and false.
2

http://phpjs.org/functions/array_key_exists:323

This is a great site for PHP programmers moving to js.

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.