我正在使用Angular 4創建前端,並且遇到了一個奇怪的錯誤。每當我執行下面的代碼:無法遍歷角4中的地圖
private createProductTree(productData: Map<number, any>): Map<number, Node> {
const productTree = new Map<number, Node>();
// Iterate over menu-item objects.
for (let key of productData.keys()) {
const product = productData.get(key);
if (product.type === 'menu-item') {
const node = new Node(product);
productTree.set(key, node);
}
}
return productTree;
}
我得到以下錯誤:在for (... of ...)
線Type 'IterableIterator<number>' is not an array type or a string type.
。
我不知道我在做什麼錯。 for
代碼與我看到的代碼here相同。
根據[討論](https://github.com/ Microsoft/TypeScript/issues/6842),它可能與您定位的Javascript版本有關。它應該適用於ES6。 – ConnorsFan
@ConnorsFan,即使在es6中,這也不是迭代Map的正確方法,正如我在答案中提到的。如果使用'keys()',則不需要使用'for..of'。 'forEach'將是更好的選擇 –