Check if an array item is set in JS

112,892

Solution 1

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;

Solution 2

var assoc_pagine = new Array();
assoc_pagine["home"]=0;

Don't use an Array for this. Arrays are for numerically-indexed lists. Just use a plain Object ({}).

What you are thinking of with the 'undefined' string is probably this:

if (typeof assoc_pagine[key]!=='undefined')

This is (more or less) the same as saying

if (assoc_pagine[key]!==undefined)

However, either way this is a bit ugly. You're dereferencing a key that may not exist (which would be an error in any more sensible language), and relying on JavaScript's weird hack of giving you the special undefined value for non-existent properties.

This also doesn't quite tell you if the property really wasn't there, or if it was there but explicitly set to the undefined value.

This is a more explicit, readable and IMO all-round better approach:

if (key in assoc_pagine)

Solution 3

var is a statement... so it's a reserved word... So just call it another way. And that's a better way of doing it (=== is better than ==)

if(typeof array[name] !== 'undefined') {
    alert("Has var");
} else {
    alert("Doesn't have var");
}

Solution 4

This is not an Array. Better declare it like this:

var assoc_pagine = {};
assoc_pagine["home"]=0;
assoc_pagine["about"]=1;
assoc_pagine["work"]=2;

or

var assoc_pagine = {
                 home:0,
                 about:1,
                 work:2
               };

To check if an object contains some label you simply do something like this:

if('work' in assoc_pagine){
   // do your thing
};

Solution 5

This worked for me

if (assoc_pagine[var] != undefined) {

instead this

if (assoc_pagine[var] != "undefined") {
Share:
112,892
Gusepo
Author by

Gusepo

Updated on February 23, 2020

Comments

  • Gusepo
    Gusepo over 4 years

    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

  • James
    James about 14 years
    The only answer that seems to address the obvious problem of using an array as an associative array. +1
  • Amit Patil
    Amit Patil about 14 years
    (Having said that, it does work, because Array is a subclass of Object. It just doesn't get you anything, other than a load more properties on the prototype to potentially clash with.)
  • KooiInc
    KooiInc about 14 years
    Oops, overlooked Bobinces answer, which tells you all and more than you wanted to know
  • xavierm02
    xavierm02 about 14 years
    Could someone explain me why I'm -2 ?
  • jozxyqk
    jozxyqk over 10 years
    "var is a reserved word in JavaScript" should be first
  • Stefan
    Stefan over 10 years
    @jozxqk, fixed. And a bit of cleanup.
  • Erick Robertson
    Erick Robertson over 10 years
    -1 this is a mess. it's really hard to get an answer out of this. All I want to know is how to check to see if an array item is set in Javascript. This is what I searched for to find this answer, and this is a very low quality answer.
  • Omn
    Omn over 9 years
    @ErickRobertson this answer may be simple, but it is also incorrect.
  • Omn
    Omn over 9 years
    This answer does address the use cased needed by the OP, however you want to use 'hasOwnProperty' not 'in' since 'in' also checks for inherited properties. (e.g. 'hasOwnProperty in {} === true )
  • Omn
    Omn over 9 years
    you want to use 'hasOwnProperty' not 'in' since 'in' also checks for inherited properties. (e.g. 'hasOwnProperty in {} === true )
  • Omn
    Omn over 9 years
    you want to use 'hasOwnProperty' not 'in' since 'in' also checks for inherited properties. (e.g. 'hasOwnProperty in {} === true )
  • Erick Robertson
    Erick Robertson over 9 years
    Thanks, @Omn ! This response worked for me, but I can see there's an easier answer. Unfortunately, it was buried at the bottom of the accepted answer. So I moved it to the top, and now it's much more clear!
  • Exlord
    Exlord almost 8 years
    also its better to define on on object like this var obj = {};, its recommended not to use new keyword for creating a empty object.
  • Kaushik
    Kaushik over 5 years
    this can be done using > -1 not > 0 and by the way this same answer is already added link
  • Bilbonic
    Bilbonic over 2 years
    Using the new Object() worked great for me, might be a cleaner way of doing it, but I used: if(typeof assoc_pagine['key'] != 'undefined'){ //do stuff here}