angular - 在 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);
问候
解决方案
你想categorizedProductsPath
成为一个嵌套数组number[][]
。但目前它是一个空数组,您没有正确初始化它。
const arr = new Array(3)
只会给你三个数组undefined
。如果你想要一个由其他三个空数组组成的数组,比如[[], [], []]
,这就是你要做的:
const arr = new Array(3).fill(0).map(() => [])
推荐阅读
- javascript - 在javascript中调用匿名函数
- assembly - 装配控制台模式一字符
- css - 重复的图标背景
- multithreading - OPENMP taskyield 指令在混合(openmp + mpi)程序中不产生任务
- javascript - 如何使用 Python 创建 API 页面
- ruby-on-rails - 机架 CORS 仅在模型中工作
- odata - 失败原因:“未找到主机”收到状态代码:“502” - 在 SAP cockpit 中创建目标
- php - 未收到 laravel 数据表中的数据
- css - 如何在 CSS 中制作不褪色动画
- solidity - 松露不识别构造函数大小变化