Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS: Associative array access over variable?

after progging php since 3 years, im hanging at javascript. Is it possible to get value of an assoziative array with a variable? Example:

var a = new Array();
a["ANDI"] = "USER";
var test = "ANDI";

alert(a[test]);

Any suggestions, how I could workaround that? Maybe with objects?

Thx for help!

like image 257
ayk Avatar asked Feb 05 '26 08:02

ayk


2 Answers

Arrays are indexed by numbers. Objects have properties that can be accessed by name.

var myContainer = {
  'User': 'Andy'
};

var key = 'User';

myContainer[key]; // Returns 'Andy'.
like image 77
g.d.d.c Avatar answered Feb 07 '26 21:02

g.d.d.c


Yup. That should alert USER.

But JavaScript has objects. If you want to do that, you'd probably want..

var a = {
    "ANDI": "USER"
};

For more details of JavaScript's object notations, check out JSON.org.

like image 43
McKayla Avatar answered Feb 07 '26 21:02

McKayla