如何使用变量访问对象属性

时间:2012-06-29 04:31:52

标签: javascript variables object properties

我有一个对象

var Messages = {
'fullName' : 'Tell us your cool name dude..! e.g. Yousuf Iqbal',
'userName' : 'Choose a catchy username. Remember! It should be available :)',
'password' : 'Choose a top secret password with special chars, numbers and alphabets',
'rePassword' : 'Retype the password you just typed. But, don\'t try to copy!',
'bYear' : 'Tell the year, in which this bomb blasted'
};

和变量..

var attribute = $('#userinfo form input').attr('name');

现在我想使用这个变量选择Messages对象属性..

var message = Messages.attribute;

但它不起作用.. 并且还尝试了以下内容..

var message = Messages+'.'+attribute;

2 个答案:

答案 0 :(得分:42)

方括号:

message = Messages[ attribute ];

答案 1 :(得分:5)

var message = Messages[attribute];