javascript 如何使用变量访问对象属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11256091/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 12:34:05 来源:igfitidea点击:
how to access object property using variable
提问by Yousuf Memon
I have an object
我有一个对象
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'
};
and a variable..
和一个变量..
var attribute = $('#userinfo form input').attr('name');
now i want to select Messages object property using this variable like this..
现在我想像这样使用这个变量来选择消息对象属性..
var message = Messages.attribute;
but Its not working.. and have also tried the following..
但它不起作用..并且还尝试了以下..
var message = Messages+'.'+attribute;
回答by Pointy
Square brackets:
方括号:
message = Messages[ attribute ];
回答by Lior Cohen
var message = Messages[attribute];