Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if an array item is set in JS

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

like image 412
Gusepo Avatar asked Apr 10 '10 11:04

Gusepo


People also ask

How do you check if a set has an array?

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!

How do you check if an array is defined in JavaScript?

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.

How do you check if an array contains a value JS?

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.

How do you check if an element is in a set in JavaScript?

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.


1 Answers

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; 
like image 130
Stefan Avatar answered Oct 06 '22 16:10

Stefan