问题
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