【发布时间】:2018-07-06 17:41:07
【问题描述】:
我正在尝试将push() 的属性指向对象counterType,但出现以下错误:
未捕获的类型错误:无法读取未定义的属性“推送”
我正在尝试从 JSON 文件中获取特定数据并将其添加到 counterType 对象。我的代码如下:
let ret = JSON.parse(this.responseText);
let counterType: any = {};
for (let i = 0; i < ret.topdownGranularities.TOPDOWN_SYSTEM_DATA.rows.length; i++) {
let row = ret.topdownGranularities.TOPDOWN_SYSTEM_DATA.rows[i];
let row_system = row.SYSTEM;
if (row.hasOwnProperty("SYSTEM")) {
counterType[row_system].push({ name: row_system, checked: true });
// counterType[row_system] = "name: " + row_system + ", checked: " + true;
}
}
此行有效,但每次迭代仅添加一个属性,因为它只是将 counterType[row_system] 的值每次重新定义为同一事物:
// counterType[row_system] = "name: " + row_system + ", checked: " + true;
我想在每次迭代时不断将{ name: row_system, checked: true } 添加到对象中。
【问题讨论】:
-
counterType[row_system]未定义。 -
您可以在
counterType[row_system].push(...)之前添加counterType[row_system] === undefined && (counterType[row_system] = [])语句。 -
@Titus 这是如何以及为什么起作用的?这是您知道解决此问题的唯一方法吗?
-
@StefanNicolaou 它的作用是检查
counterType[row_system]是否为undefined,如果是,则将其设置为空数组。您可以使用if语句if(!counterType[row_system]){ counterType[row_system] = []; }来做同样的事情
标签: javascript json typescript object