简体   繁体   中英

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. 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(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.

You can use a for loop to iterate over your objects..

var obj = sample.namespace.Fruit;

for(var key in obj) {
    console.log("Fruit :: " + key + " -- " + obj[key])
}

Check Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM