Looping through object in JavaScript
if(properties != undefined)
{
foreach(key in properties)
{
dialogProperty.key = property[key];
}
开发者_运维技巧 alert(dialogProperty.close);
}
How can I achieve/fix the above code? I think the above code is self explanatory.
I think you mean for
rather than foreach
. You should also stop key
being global and use Object.prototype.hasOwnProperty
:
if(properties != undefined)
{
for (var key in properties)
{
if (properties.hasOwnProperty(key) {
dialogProperty[key] = properties[key]; // fixed this variable name too
}
}
alert(dialogProperty.close);
}
NB Incorporated Kobi's fix too.
Assuming you're trying to copy all properties, you're probably looking for:
dialogProperty[key] = property[key];
dialogProperty.key
is not dynamic, it sets the key
property each time, the same way dialogProperty["key"]
would.
properties && Object.keys(properties).forEach(function(key) {
dialogProperty[key] = properties[key];
});
console.log(dialogProperty.close);
The properties &&
check is to ensure that properties is not falsy.
The Object.keys
call returns an array of all keys that the properties
object has.
.forEach
runs a function for each element in the array.
dialogProperty[key] = properties[key]
set's the value of dialogProperty to be that of properties.
精彩评论