39

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

Kevin Reid
  • 37,492
  • 13
  • 80
  • 108
Gusepo
  • 837
  • 2
  • 13
  • 26
  • 4
    Arrays in javascript do not use associative keys. When you set an "associative key" on an array, you are actually setting a property on that array object, not an element of that array. This means that the "associative key" will not be iterated over when using Array.forEach() and will not be included when calculating Array.length. If you want "associative arrays" use an object as mentioned below. If you want to see if an object has a property, see this answer: http://stackoverflow.com/questions/135448/how-do-i-check-if-an-object-has-a-property-in-javascript – Omn Jan 04 '15 at 03:19

9 Answers9

77

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;
Erick Robertson
  • 32,125
  • 13
  • 69
  • 98
Stefan
  • 9,289
  • 7
  • 38
  • 46
  • *"`var` is a reserved word in JavaScript"* should be first – jozxyqk Dec 07 '13 at 09:21
  • @jozxqk, fixed. And a bit of cleanup. – Stefan Jan 28 '14 at 09:21
  • 7
    -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. – Erick Robertson Mar 25 '14 at 04:47
  • you want to use 'hasOwnProperty' not 'in' since 'in' also checks for inherited properties. (e.g. 'hasOwnProperty in {} === true ) – Omn Jan 21 '15 at 20:20
  • also its better to define on on object like this `var obj = {};`, its recommended not to use `new` keyword for creating a empty object. – Exlord Aug 07 '16 at 09:33
  • 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} – Bilbonic Jan 21 '22 at 23:20
17
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)
bobince
  • 528,062
  • 107
  • 651
  • 834
  • The only answer that seems to address the obvious problem of using an array as an associative array. +1 – James Apr 10 '10 at 12:10
  • 1
    (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.) – bobince Apr 10 '10 at 12:32
  • you want to use 'hasOwnProperty' not 'in' since 'in' also checks for inherited properties. (e.g. 'hasOwnProperty in {} === true ) – Omn Jan 21 '15 at 20:19
9

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");
}
xavierm02
  • 8,457
  • 1
  • 20
  • 24
  • Could someone explain me why I'm -2 ? – xavierm02 Apr 10 '10 at 17:01
  • 1
    @ErickRobertson this answer may be simple, but it is also incorrect. – Omn Jan 21 '15 at 20:08
  • 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! – Erick Robertson Jan 21 '15 at 21:49
3

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
};
KooiInc
  • 119,216
  • 31
  • 141
  • 177
  • Oops, overlooked Bobinces answer, which tells you all and more than you wanted to know – KooiInc Apr 10 '10 at 15:18
  • 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 Jan 21 '15 at 20:13
2

This worked for me

if (assoc_pagine[var] != undefined) {

instead this

if (assoc_pagine[var] != "undefined") {
Anton Perera
  • 353
  • 3
  • 9
1

TLDR; The best I can come up with is this: (Depending on your use case, there are a number of ways to optimize this function.)

function arrayIndexExists(array, index){
    if ( typeof index !== 'number' && index === parseInt(index).toString()) {
        index = parseInt(index);
    } else {
        return false;//to avoid checking typeof again
    }
    return typeof index === 'number' && index % 1===0 && index >= 0 && array.hasOwnKey(index);
}

The other answer's examples get close and will work for some (probably most) purposes, but are technically quite incorrect for reasons I explain below.

Javascript arrays only use 'numerical' keys. When you set an "associative key" on an array, you are actually setting a property on that array object, not an element of that array. For example, this means that the "associative key" will not be iterated over when using Array.forEach() and will not be included when calculating Array.length. (The exception for this is strings like '0' will resolve to an element of the array, but strings like ' 0' won't.)

Additionally, checking array element or object property that doesn't exist does evaluate as undefined, but that doesn't actually tell you that the array element or object property hasn't been set yet. For example, undefined is also the result you get by calling a function that doesn't terminate with a return statement. This could lead to some strange errors and difficulty debugging code.

This can be confusing, but can be explored very easily using your browser's javascript console. (I used chrome, each comment indicates the evaluated value of the line before it.);

var foo = new Array();
foo;
//[]
foo.length;
//0
foo['bar'] = 'bar';
//"bar"
foo;
//[]
foo.length;
//0
foo.bar;
//"bar"

This shows that associative keys are not used to access elements in the array, but for properties of the object.

foo[0] = 0;
//0
foo;
//[0]
foo.length;
//1
foo[2] = undefined
//undefined
typeof foo[2]
//"undefined"
foo.length
//3

This shows that checking typeof doesn't allow you to see if an element has been set.

var foo = new Array();
//undefined
foo;
//[]
foo[0] = 0;
//0
foo['0']
//0
foo[' 0']
//undefined

This shows the exception I mentioned above and why you can't just use parseInt();

If you want to use associative arrays, you are better off using simple objects as other answers have recommended.

Omn
  • 2,982
  • 1
  • 26
  • 39
1
if (assoc_pagine.indexOf('home') > -1) {
   // we have home element in the assoc_pagine array
}

Mozilla indexOf

0
function isset(key){
ret = false;
array_example.forEach(function(entry) {
  if( entry == key ){
    ret = true;
  }
});
return ret;
}

alert( isset("key_search") );
ProgramFOX
  • 6,131
  • 11
  • 45
  • 51
0

The most effective way:

if (array.indexOf(element) > -1) {
   alert('Bingooo')
}

W3Schools

Darlan Dieterich
  • 2,369
  • 1
  • 27
  • 37
  • this can be done using `> -1` not `> 0` and by the way this same answer is already added [link](https://stackoverflow.com/a/49735714/2845389) – Kaushik Feb 22 '19 at 07:04