【问题标题】:TypeError: Cannot read property '0' of undefined in AngularjsTypeError:无法读取 Angularjs 中未定义的属性“0”
【发布时间】:2019-03-21 10:52:28
【问题描述】:

我看到了很多与 TypeError: Cannot read property '0' of undefined 但它们都无助于解决我的错误。

我的要求是 onClick 按钮(例如:ng-click="addRow(tester.devices)" )我必须调用一个函数-

如果已经存在/调用设备列表,则无需定义_scope.tester.devices = [],否则定义_scope.tester.devices = [];以避免错误: 无法读取未定义的属性“unshift”

我的代码如下

_scope.addRow = function (list) {
        _scope.uniqueId = Math.round((Math.random() * 10) * 10000);
        if (_scope.tester.devices) {
            _scope.tester.devices.unshift({
                'name': '',
                'id': '',
                'uniqueId': _scope.uniqueId,
            });


        } else {
            _scope.tester.devices = [];
            _scope.tester.devices.unshift({
                'name': '',
                'id': '',
                'uniqueId': _scope.uniqueId,
            });
        }
        _scope.modifyField[list[0].uniqueId] = true;
    }

Edit1:我将 $scope 定义为 _scope。所以这不是问题。

这个问题解决了

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    将数组传递给函数,好像你将错误的参数传递给函数_scope.addRow()

    将数组传递给函数后对我来说效果很好。

    【讨论】:

    • 我在控制器函数中将 $scope 定义为 _scope。问题出在 _scope.modifyField 上。我解决了。感谢帮助
    【解决方案2】:

    我通过将 _scope.modifyField[list[0].uniqueId] = true; 修改为 _scope.modifyField[_scope.uniqueId] = true; 解决了这个问题。

    不幸的是,我无法删除我的问题,因为有人按照 Stack Overflow 规则为此投入了时间。

    代码如下:

     _scope.addRow = function (list) {
            _scope.uniqueId = Math.round((Math.random() * 10) * 10000);
            if (_scope.tester.devices) {
                _scope.tester.devices.unshift({
                    'name': '',
                    'id': '',
                    'uniqueId': _scope.uniqueId,
                });
                 _scope.modifyField[list[0].uniqueId] = true;
    
            } else {
                _scope.tester.devices = [];
                _scope.tester.devices.unshift({
                    'name': '',
                    'id': '',
                    'uniqueId': _scope.uniqueId,
                });
            }
            _scope.modifyField[_scope.uniqueId] = true;
        }
    

    【讨论】:

      【解决方案3】:

      嗨, 你确定你的函数参数('list')是一个数组吗?它似乎未定义。

      【讨论】:

      • 不,是函数的参数,未定义。抛出错误是因为您尝试像访问数组一样访问它。现在,如果您不再需要它,可以从方法定义中删除它:code _scope.addRow = function () { code
      猜你喜欢
      • 2020-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-26
      • 2016-09-12
      • 2016-11-20
      相关资源
      最近更新 更多