首页 > 解决方案 > 为什么Angular会将索引0数组推入子数组而不是索引1?

问题描述

我的 oninit 中有以下数组设置:

 this.tests = [{
      status: 0,
      testresults: [{       
        name: 'test',
          id: 1
      }]
    }
    ]
    ;

    this.tests.push([{
      status: 1,
      testresults: [{       
        name: 'test2',
          id: 2
      }]
    }
    ]
    }]);

该数组按预期工作。我的目标是将查询结果推送到测试内部的 testresults 数组中。

  this.tests[0].testresults.push(this.qryresults);
  this.tests[1].testresults.push(this.qryresults);

索引 0 正常工作,索引 1 返回以下错误:

"ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'push' of undefined
TypeError: Cannot read property 'push' of undefined"

标签: javascriptarraysangulartypescript

解决方案


您第二次推送一个数组而不是一个额外的对象,这会导致错误,因为您推送的数组没有属性testresults。请参阅下面的代码片段以获取代码的工作版本:

(function() {
  this.qryresults = "some test data"
  this.tests = [{
    status: 0,
    testresults: [{
      name: 'test',
      id: 1
    }]
  }];

  this.tests.push({ // <--- removed [ here
    status: 1,
    testresults: [{
      name: 'test2',
      id: 2
    }]
  });              // <--- removed ] here

  this.tests[0].testresults.push(this.qryresults);
  this.tests[1].testresults.push(this.qryresults);
  console.log(this.tests)
})()


推荐阅读