首页 > 解决方案 > 在 Angular 中初始化二维数组的问题

问题描述

我在初始化“categorizedProductsPath”数组时遇到问题,两种方法都不起作用,失败在哪里?

      // let categorizedProductsPath: number[][] = [];
      let categorizedProductsPath = new Array<number[]>(categorizedProducts.length);
      for (let k = 0; k < categorizedProducts.length; k++) {
        const categorizedProduct = categorizedProducts[k];
        const categoryOfCategorizedProduct = await this.getCategoryToProduct(+categorizedProduct.google_product_category);

        let currentParentId = categoryOfCategorizedProduct.parentId;
        while (currentParentId !== 0) {
          const parentCategory = await this.getCategoryToProduct(currentParentId);
          currentParentId = parentCategory.id;
          categorizedProductsPath[categorizedProduct.id].push(parentCategory.id); //***
        }
      }

错误(TypeError: Cannot read properties of undefined (reading 'push'))来这里***:

categorizedProductsPath[categorizedProduct.id].push(parentCategory.id);

问候

标签: angulartypescript

解决方案


你想categorizedProductsPath成为一个嵌套数组number[][]。但目前它是一个空数组,您没有正确初始化它。

const arr = new Array(3)只会给你三个数组undefined。如果你想要一个由其他三个空数组组成的数组,比如[[], [], []],这就是你要做的:

const arr = new Array(3).fill(0).map(() => [])

推荐阅读