Search code examples
javascriptarraysisset

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


Solution

  • 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;