最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin2浏览0评论

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?

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?

Share Improve this question edited Sep 19, 2012 at 19:40 James McMahon 49.6k69 gold badges210 silver badges288 bronze badges asked Apr 19, 2010 at 0:59 joejoesonjoejoeson 1,1071 gold badge10 silver badges14 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 10

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];
}

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();.

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

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论