javascript - 为什么 Angular 会将索引 0 数组插入子数组而不是索引 1?

标签 javascript arrays angular typescript

我的 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"

最佳答案

您第二次推送一个数组而不是一个额外的对象,这会导致错误,因为您推送的数组没有属性 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)
})()

关于javascript - 为什么 Angular 会将索引 0 数组插入子数组而不是索引 1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66392717/

相关文章:

c++ - 新的数组分配

C 使用常量声明二维数组

android - 相当于 Ionic 2 中的 setOnItemLongClickListener

forms - 使用组件的 Angular 2 表单级别验证

javascript - 设置 highcharts datalabels 的背景颜色与其系列的颜色相同

javascript - 在 JavaScript 对象中堆叠过滤器值不起作用

javascript - 如何在nodejs中正确使用async和await?

javascript - 如何在 Angularjs 中更改 json 数据

c - 不使用指针对多维数组进行排序

http - 使用参数动态加载页面(Ionic 2 + Angular 2)