[英]How do I iterate over an object within a Soy file when using Google closure templates?
[英]How do I iterate over enum values in Google Closure?
我正在嘗試找到迭代Google Closure中定義的枚舉上的所有值的最佳方法。 假設我定義了以下枚舉:
/**
* @enum {number}
*/
sample.namespace.Fruit = {
Orange: 0,
Apple: 1,
Banana: 2
};
現在,我看到這樣做的最好方法是這樣的:
for (var key in sample.namespace.Fruit) {
var fruit = /** @type {sample.namespace.Fruit} */ (sample.namespace.Fruit[key]);
// Make a smoothie or something.
}
我覺得讀書很痛苦。 我正在列出一個名稱空間三次,只是為了讓編譯器出現。 我應該使用另一種迭代技術嗎? 這是完成這種迭代形式的最佳方法嗎?
您可以使用goog.object.forEach
來避免名稱空間重復。
goog.object.forEach(sample.namespace.Fruit,
function(value, key, allValues) {
// Make some delicious fruit jellies or something.
});
作為旁注,在大多數情況下,您希望避免為@enums使用字符串鍵,以便編譯器可以重命名這些鍵。
您可以使用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.