Angular初始化二维数组触发Cannot read properties of undefined错误求助
报错原因
- 二维数组仅完成外层初始化,内层子数组未赋值:执行
new Array<number[]>(categorizedProducts.length)只会创建一个指定长度的空数组,所有位置的默认值都是undefined,没有自动生成空的子数组,直接调用push方法自然会触发读取undefined属性的错误。 - 数组下标不匹配:你初始化外层数组的长度是
categorizedProducts.length,但实际访问数组时用的下标是categorizedProduct.id,如果商品id不是从0开始的连续整数、或者id最大值超过了外层数组的长度,对应下标的位置天然就是undefined,也会触发该报错。
修复方案
方案1:适配商品id连续的场景
如果确认所有商品的id是从0开始、连续、且最大值等于categorizedProducts.length - 1,可以直接在循环内先初始化对应下标的子数组再操作:
let categorizedProductsPath = new Array<number[]>(categorizedProducts.length); for (let k = 0; k < categorizedProducts.length; k++) { const categorizedProduct = categorizedProducts[k]; // 先给对应id的位置初始化空数组 if (!categorizedProductsPath[categorizedProduct.id]) { categorizedProductsPath[categorizedProduct.id] = []; } 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); } }
方案2:适配商品id不连续/数值较大的场景
如果商品id存在跳号、或者数值较大,更推荐用键值对结构存储,避免数组空间浪费和下标越界问题:
// 用Record类型存储,key为商品id,value为路径数组 const categorizedProductsPath: Record<number, number[]> = {}; for (let k = 0; k < categorizedProducts.length; k++) { const categorizedProduct = categorizedProducts[k]; // 不存在对应id的数组时先初始化 if (!categorizedProductsPath[categorizedProduct.id]) { categorizedProductsPath[categorizedProduct.id] = []; } 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); } }
内容的提问来源于stack exchange,提问作者meDom
相关产品推荐
相关产品推荐

