开发者

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!


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


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜