Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
20
rated 0 times [  21] [ 1]  / answers: 1 / hits: 124858  / 14 Years ago, sat, april 10, 2010, 12:00:00

I've got an array



    var assoc_pagine = new Array();
assoc_pagine[home]=0;
assoc_pagine[about]=1;
assoc_pagine[work]=2;


I tried



    if (assoc_pagine[var] != undefined) {


but it doesn't seem to work



I'm using jquery, I don't know if it can help



Thanks


More From » arrays

 Answers
8

Use the in keyword to test if a attribute is defined in a object



if (assoc_var in assoc_pagine)


OR



if (home in assoc_pagine)





There are quite a few issues here.



Firstly, is var supposed to a variable has the value home, work or about? Or did you mean to inspect actual property called var?



If var is supposed to be a variable that has a string value, please note that var is a reserved word in JavaScript and you will need to use another name, such as assoc_var.



var assoc_var = home;
assoc_pagine[assoc_var] // equals 0 in your example


If you meant to inspect the property called var, then you simple need to put it inside of quotes.



assoc_pagine[var]


Then, undefined is not the same as undefined. You will need typeof to get the string representation of the objects type.



This is a breakdown of all the steps.



var assoc_var = home; 
var value = assoc_pagine[assoc_var]; // 0
var typeofValue = typeof value; // number


So to fix your problem



if (typeof assoc_pagine[assoc_var] != undefined) 





update: As other answers have indicated, using a array is not the best sollution for this problem. Consider using a Object instead.



var assoc_pagine = new Object();
assoc_pagine[home]=0;
assoc_pagine[about]=1;
assoc_pagine[work]=2;

[#97116] Tuesday, April 6, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jamaal

Total Points: 515
Total Questions: 102
Total Answers: 107

Location: France
Member since Thu, May 6, 2021
3 Years ago
;