Tec*_*ium 4 javascript iteration enums google-closure google-closure-library
我正在尝试找到迭代Google Closure中定义的枚举上的所有值的最佳方法.假设我定义了以下枚举:
/**
* @enum {number}
*/
sample.namespace.Fruit = {
Orange: 0,
Apple: 1,
Banana: 2
};
Run Code Online (Sandbox Code Playgroud)
现在,我看到这样做的最好方法是这样的:
for (var key in sample.namespace.Fruit) {
var fruit = /** @type {sample.namespace.Fruit} */ (sample.namespace.Fruit[key]);
// Make a smoothie or something.
}
Run Code Online (Sandbox Code Playgroud)
我觉得读书很痛苦.我正在列出一个名称空间三次,只是为了让编译器出现.我应该使用另一种迭代技术吗?这是完成这种迭代形式的最佳方法吗?
您可以使用goog.object.forEach以避免名称空间重复.
goog.object.forEach(sample.namespace.Fruit,
function(value, key, allValues) {
// Make some delicious fruit jellies or something.
});
Run Code Online (Sandbox Code Playgroud)
作为旁注,在大多数情况下,您希望避免为@enums使用字符串键,以便编译器可以重命名这些键.