In Javascript, how do I convert a string so it can be used to call a property?

给你一囗甜甜゛ 提交于 2020-01-01 12:07:07

问题


So, I have an associative array and the keys in the array are properties of an object. I want to loop through the array and in each interation do something like this:

Object.key

This however does not work and results in returning undefined rather than the value of the property.

Is there a way to do this?


回答1:


You can use a for ... in loop:

for (var key in obj) {
    //key is a string containing the property name.

    if (!obj.hasOwnProperty(key)) continue;  //Skip properties inherited from the prototype

    var value = obj[key];
}



回答2:


You should use the bracket notation property accessor:

var value = object[key];

This operator can even evaluate expressions, e.g.:

var value = object[condition ? 'key1' : 'key2'];

More info:

  • Member operators

Don't forget that the methods of Array objects, expect to work with numeric indexes, you can add any property name, but it isn't recommended, so instead intantiating an Array object (i.e. var obj = []; or var obj = new Array(); you can use a simple object instance (i.e. var obj = {} or var obj = new Object();.




回答3:


Yes. Assuming key is a string, try myObject[key]



来源:https://stackoverflow.com/questions/2664660/in-javascript-how-do-i-convert-a-string-so-it-can-be-used-to-call-a-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!