简体   繁体   English

如何使用字符串变量访问 object 属性?

[英]How to access object property using string variable?

If I have an object like below:如果我有一个 object,如下所示:

this.state = {
  like: {
    count: 100,
    clicked: false
  },
  dislike: {
    count: 25,
    clicked: false
  }
};

If have a variable name of var prop = 'like' , how can I get the value of this.state.like using prop value?如果有一个变量名var prop = 'like' ,如何使用prop值获取this.state.like的值?

I tried named property [this.state.prop] but it's not working.我尝试了命名属性[this.state.prop]但它不起作用。

You can use bracket notation:您可以使用括号表示法:

var prop = 'like';

var like = this.state[prop];

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

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