[英]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
. 我想你的意思
for
,而不是foreach
。 You should also stop key
being global and use Object.prototype.hasOwnProperty
: 您还应该停止全局
key
,并使用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. NB Incorporated Kobi也修复了该问题。
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. dialogProperty.key
不是动态的,它每次都设置key
属性,就像dialogProperty["key"]
一样。
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. properties &&
检查是为了确保属性不虚假。
The Object.keys
call returns an array of all keys that the properties
object has. Object.keys
调用返回properties
对象具有的所有键的数组。
.forEach
runs a function for each element in the array. .forEach
为数组中的每个元素运行一个函数。
dialogProperty[key] = properties[key]
set's the value of dialogProperty to be that of properties. dialogProperty[key] = properties[key]
设置dialogProperty的值为属性值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.