简体   繁体   English

如何迭代Google Closure中的枚举值?

[英]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])
}

Check Fiddle 检查小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用Google闭包模板时,如何在Soy文件中迭代对象? - How do I iterate over an object within a Soy file when using Google closure templates? 如何遍历google文档中的所有元素? - How do I Iterate over all elements in a google document? Javascript-如何遍历对象中键的值? - Javascript - How do I iterate over values of keys in an object? 如何迭代和比较 JS Object 中的值? - How do I iterate over and compare values in a JS Object? Google关闭:如何在元素上设置可见 - Google Closure: How do I setVisible on an Element 我如何在 react.js 中遍历 object 数组并在 object 中添加价格值,如下所示 - How do i iterate over an array of object in react.js and add the values of prices in the object as shown below 是否可以在 Google Apps 脚本中迭代 ENUM? - Is it possible to iterate over ENUM's in Google Apps Script? 如何在 Google Apps Scripts 字典中使用数组作为键,并在遍历字典时保持其数组结构 - How do I use an array as a key in a Google Apps Scripts dictionary and have it maintain its array structure while I iterate over the dictionary 如何为Google Closure Compiler启用日志记录? - How do I enable logging for Google Closure Compiler? 迭代枚举时如何排除命名空间函数? - How do i exclude namespace functions when iterating over an enum?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM