【问题标题】:TypeError: Cannot read property 'push' of undefined with AngularJSTypeError:无法使用 AngularJS 读取未定义的属性“推送”
【发布时间】:2018-08-29 17:11:50
【问题描述】:

我正在尝试将我的数据推送到此CompareArray,但出现以下错误:

TypeError: Cannot read property 'push' of undefined
    at Object.addResult (src\services\CompareService.js:22)

代码:

this.addResult = function (type, result) {
    this[type.toLowerCase() + 'CompareArray'].push(result);
    this.checkToDisplayLinks(type);
    this.checkToDisableCheckboxes(type);
};

【问题讨论】:

  • 表示this[type.toLowerCase() + 'CompareArray'] 未定义
  • angularjs 标签适用于 Angular JS(即 v1),而 angular 标签适用于 Angular(即 2+),因此只有一个标签可以相关。你能把不正确的删掉吗? (我相信代码是AngularJS,所以去掉angular标签)

标签: javascript arrays angularjs


【解决方案1】:

如果你仔细观察,错误是自我描述的。

Cannot read property 'push' of undefined at Object.addResult 

addResult 是你的方法。你正在“推”上

this[type.toLowerCase() + 'CompareArray'].push(result);

它说 - 未定义的“推送”。这意味着

this[type.toLowerCase() + 'CompareArray'] 

未定义。 Push 是一种仅适用于数组的方法。

希望这会有所帮助。

【讨论】:

    【解决方案2】:

    在你推送任何东西之前,检查它是否未定义和初始化

    if(this[type.toLowerCase() + 'CompareArray']){
     this[type.toLowerCase() +  'CompareArray'].push(result);
    }
    else
    {
       this[type.toLowerCase() +  'CompareArray'] = [result];
    }
    

    【讨论】:

    • 嗯.....所以它的编写方式不会添加任何结果,我对其进行了编辑,因此它会在定义数组时添加值
    猜你喜欢
    • 2016-05-06
    • 1970-01-01
    • 2020-04-20
    • 2017-11-23
    • 1970-01-01
    • 1970-01-01
    • 2021-07-23
    • 2015-07-10
    • 1970-01-01
    相关资源
    最近更新 更多