[英]How do I iterate over enum values in Google Closure?
I'm trying to find the best way to iterate over all of the values on an enum defined in Google Closure. 我正在尝试找到迭代Google Closure中定义的枚举上的所有值的最佳方法。 Let's say I have the following enum defined:
假设我定义了以下枚举:
/**
* @enum {number}
*/
sample.namespace.Fruit = {
Orange: 0,
Apple: 1,
Banana: 2
};
Right now, the best way I've seen to do this would be something like this: 现在,我看到这样做的最好方法是这样的:
for (var key in sample.namespace.Fruit) {
var fruit = /** @type {sample.namespace.Fruit} */ (sample.namespace.Fruit[key]);
// Make a smoothie or something.
}
I consider that painful to read. 我觉得读书很痛苦。 I'm listing a namespace three times just to get the compiler to come along for the ride.
我正在列出一个名称空间三次,只是为了让编译器出现。 Is there another iteration technique that I should be using instead?
我应该使用另一种迭代技术吗? Is this the best way to accomplish this form of iteration?
这是完成这种迭代形式的最佳方法吗?
You can use goog.object.forEach
to avoid namespace repetition. 您可以使用
goog.object.forEach
来避免名称空间重复。
goog.object.forEach(sample.namespace.Fruit,
function(value, key, allValues) {
// Make some delicious fruit jellies or something.
});
As a side note, in most cases you want to avoid using string keys for @enums so the compiler can rename those. 作为旁注,在大多数情况下,您希望避免为@enums使用字符串键,以便编译器可以重命名这些键。
You can use a for loop to iterate over your objects.. 您可以使用for循环迭代对象..
var obj = sample.namespace.Fruit;
for(var key in obj) {
console.log("Fruit :: " + key + " -- " + obj[key])
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.