How to iterate over enumeration values ​​in Google Closure?

I am trying to find the best way to iterate over all the values ​​in an enumeration defined in Google Closure. Let's say I have the following enumeration defined:

/** * @enum {number} */ sample.namespace.Fruit = { Orange: 0, Apple: 1, Banana: 2 }; 

Right now, the best way I've seen for 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 find it painful to read. I list the namespace three times to get the compiler to go on a trip. Is there any other iteration method that I should use instead? Is this the best way to do this form of iteration?

+4
source share
2 answers

You can use goog.object.forEach to avoid namespace duplication.

 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 that the compiler can rename them.

+5
source

You can use a loop to iterate over your objects.

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

Check feed

+2
source

Source: https://habr.com/ru/post/1444457/


All Articles