javascript:循环对象属性 [英] javascript: loop through object properties
问题描述
我正在动态构建一个对象:
I'm building an object dynamically like this:
scope.filters[scope.col.field] = { value: scope.filterValue, operator: scope.filterOperator };
其中scope.col.field是一个字符串。
where scope.col.field is a string.
那么我如何遍历scope.filters以访问各种属性的值和运算符?
Then how do I loop through scope.filters in order to access value and operator for the various properties ?
推荐答案
以下是一个基本示例:
for (var fieldName in scope.filters) {
if (!scope.filters.hasOwnProperty(fieldName)) {
alert(fieldName + ": " + scope.filters[fieldName]);
}
}
for..in
将遍历对象的所有成员。
for..in
will go through all the members of an object.
最佳做法是始终检查变量是否为自己的成员,所以你不要拿起任何其他继承的函数或成员。 这里是一个很好的解释和示例,说明为什么要使用 hasOwnProperty
。
It's a best practice to always check that the variable is its own member, so you don't pick up any other inherited functions or members. Here is a good explanation and example regarding why you should use hasOwnProperty
.
我只是设置了一个警报,但显然你可以为每个 fieldName $ c做任何你需要的事情$ c>及其价值。请注意,在这种情况下,您会收到很多警报。
I just set up an alert, but you can obviously do whatever you need with each fieldName
and its value. Note, in this case, you'll get a lot of alerts.
这篇关于javascript:循环对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!