Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
104
rated 0 times [  108] [ 4]  / answers: 1 / hits: 16344  / 12 Years ago, thu, august 2, 2012, 12:00:00

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?


More From » php

 Answers
228

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.


[#83905] Wednesday, August 1, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
wyattkennyc

Total Points: 650
Total Questions: 102
Total Answers: 90

Location: Monaco
Member since Mon, May 23, 2022
2 Years ago
;