【问题标题】:Why would Angular push index 0 array into a sub array and not index 1?为什么Angular会将索引0数组推入子数组而不是索引1?
【发布时间】:2021-02-26 20:58:24
【问题描述】:

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

【问题讨论】:

    标签: javascript arrays angular typescript


    【解决方案1】:

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

    (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)
    })()

    【讨论】:

      【解决方案2】:

      您将数组推送到数组。因此,您必须将对象添加到数组中:

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

      });

      【讨论】:

      • 我的代码在上面工作——我的问题是在带有索引的代码行上。 this.tests[0].testresults.push(this.qryresults); this.tests[1].testresults.push(this.qryresults);
      【解决方案3】:

      是的,您可以通过以下代码解决此问题;

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-30
        • 2017-05-22
        • 1970-01-01
        • 2023-03-30
        • 1970-01-01
        • 2016-11-04
        相关资源
        最近更新 更多