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
Use the has() method to check if a Set contains an array, e.g. set.has(arr) . The array has to be passed by reference to the has method to get a reliable result. The has method tests for the presence of a value in a Set and returns true if the value is contained in the Set . Copied!
The Array. isArray() method checks whether the passed variable is an Array object. It returns a true boolean value if the variable is an array and false if it is not.
JavaScript Array includes() The includes() method returns true if an array contains a specified value. The includes() method returns false if the value is not found.
To check if a given value exists in a set, use .has() method: mySet.has(someVal); Will return true if someVal appears in the set, false otherwise.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With