ayk
ayk

Reputation: 1340

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!

Upvotes: 2

Views: 108

Answers (3)

McKayla
McKayla

Reputation: 6949

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.

Upvotes: 3

g.d.d.c
g.d.d.c

Reputation: 47978

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'.

Upvotes: 5

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

Sure, the code you have shown works perfectly fine and prints USER as expected. Live demo: http://jsfiddle.net/htnPe/

Upvotes: 2

Related Questions