简体   繁体   English

如何通过变量值动态访问对象属性

[英]How to access object property dynamically by variable value

I'm using AJAX to send data to a controller and retrieve it. 我正在使用AJAX将数据发送到控制器并检索它。 When I have console.log(result.ans2.pass) it works. 当我有console.log(result.ans2.pass)它可以工作。

However with console.log(result.ans + x + .pass) It keeps given me an error: 但是,使用console.log(result.ans + x + .pass) ,始终出现错误:

expected expression, got '.' 预期的表达,得到“。”

 $.ajax({ type: "POST", url: 'http://some-url', dataType: "json", data: { datasent: dataKey }, cache: false, success: function(result) { var x = 2; console.log(result.ans + x + .pass) } }); 

要使用字符串访问对象的属性,您需要使用方括号表示法:

console.log(result['ans' + x].pass)

You can't dynamically add to a variable name like you're trying to do with dot notation . 您不能像尝试使用点表示法那样动态地添加变量名称。 Instead, you can use bracket notation and concatenation so that you can access your property name using a string: 相反,您可以使用方括号表示法和串联方式,以便可以使用字符串访问属性名称:

console.log(result["ans"+x].pass)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM