2

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!

4
  • 1
    You don't even need Array for that, new Object() will do. Commented Jun 13, 2011 at 19:03
  • 2
    That's actually a misuse of Array, since arrays are really meant to be numerically indexed. new Object() or just {} is the right choice. Commented Jun 13, 2011 at 19:04
  • 2
    Workaround what? Your code works. Commented Jun 13, 2011 at 19:05
  • 1
    @Matt Keep in mind they're coming from PHP. PHP doesn't have objects, only "associative" arrays. A data type made for using words to store data is a completely foreign concept for a PHP programmer. Commented Jun 13, 2011 at 20:04

3 Answers 3

5

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'.
Sign up to request clarification or add additional context in comments.

2 Comments

+1 for object over array, and object literal notation. Quoted keys are optional (unless you want to use a string which is not a valid JavaScript identifier).
Quoted keys are optional, but I use them out of habit from Python. It also prevents these pitfalls: var myContainer = { my.name: 'Value', 'My Name': 'Val2' }.
3

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.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.