How to convert string as object's field name in javascript

前端 未结 5 1034
北恋
北恋 2020-11-28 08:38

I have a js object like:

obj = {
  name: \'js\',
  age: 20
};

now i want to access name field of obj, but i can only get string \'name\', s

5条回答
  •  不知归路
    2020-11-28 09:32

    It's quite simple, to access an object's value via a variable, you use square brackets:

    var property = 'name';
    var obj = {name: 'js'};
    alert(obj[property]); // pops 'js'
    

提交回复
热议问题