Check if an array item is set in JS
Asked Answered
P

9

40

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

Profligate answered 10/4, 2010 at 11:29 Comment(1)
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: #135948Steinbok
D
79

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;
Deviation answered 10/4, 2010 at 11:31 Comment(6)
"var is a reserved word in JavaScript" should be firstWhose
@jozxqk, fixed. And a bit of cleanup.Deviation
-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.Robomb
you want to use 'hasOwnProperty' not 'in' since 'in' also checks for inherited properties. (e.g. 'hasOwnProperty in {} === true )Steinbok
also its better to define on on object like this var obj = {};, its recommended not to use new keyword for creating a empty object.Stepchild
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}Volgograd
H
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)
Heinrich answered 10/4, 2010 at 11:52 Comment(3)
The only answer that seems to address the obvious problem of using an array as an associative array. +1Saber
(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.)Heinrich
you want to use 'hasOwnProperty' not 'in' since 'in' also checks for inherited properties. (e.g. 'hasOwnProperty in {} === true )Steinbok
A
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");
}
Aegean answered 10/4, 2010 at 11:39 Comment(3)
Could someone explain me why I'm -2 ?Aegean
@ErickRobertson this answer may be simple, but it is also incorrect.Steinbok
Thanks, @Steinbok ! 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!Robomb
G
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
};
Grekin answered 10/4, 2010 at 15:7 Comment(2)
Oops, overlooked Bobinces answer, which tells you all and more than you wanted to knowGrekin
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 )Steinbok
L
2

This worked for me

if (assoc_pagine[var] != undefined) {

instead this

if (assoc_pagine[var] != "undefined") {
Logistic answered 22/2, 2019 at 6:59 Comment(0)
S
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.

Steinbok answered 4/1, 2015 at 6:49 Comment(0)
O
1
if (assoc_pagine.indexOf('home') > -1) {
   // we have home element in the assoc_pagine array
}

Mozilla indexOf

Outmost answered 9/4, 2018 at 14:45 Comment(0)
T
0
function isset(key){
ret = false;
array_example.forEach(function(entry) {
  if( entry == key ){
    ret = true;
  }
});
return ret;
}

alert( isset("key_search") );
Torey answered 18/12, 2013 at 13:28 Comment(0)
H
0

The most effective way:

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

W3Schools

Handfasting answered 30/4, 2018 at 12:2 Comment(1)
this can be done using > -1 not > 0 and by the way this same answer is already added linkRicardoricca

© 2022 - 2024 — McMap. All rights reserved.