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

前端 未结 5 1032
北恋
北恋 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:24

    You can access the properties of javascript object using the index i.e.

    var obj = {
      name: 'js',
      age: 20
    };
    
    var isSame = (obj["name"] == obj.name)
    alert(isSame);
    
    var nameIndex = "name"; // Now you can use nameIndex as an indexor of obj to get the value of property name.
    isSame = (obj[nameIndex] == obj.name)
    

    Check example@ : http://www.jsfiddle.net/W8EAr/

提交回复
热议问题