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

how to access object property using variable

本文关键字:对象 属性 访问 变量 何使用      更新时间:2023-09-26

我有一个对象

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');

现在我想像这样使用此变量选择消息对象属性。

var message = Messages.attribute;

但它不起作用..并且还尝试了以下方法。

var message = Messages+'.'+attribute;

方括号:

message = Messages[ attribute ];
var message = Messages[attribute];