简体   繁体   English

如何使用插值来访问数组索引?

[英]How do I use interpolation to access an array index?

I want to use interpolation to access a specific item at an index of my array, but it is giving me this error: "TypeError: Cannot set property '0' of undefined." 我想使用插值来访问数组索引处的特定项,但这给了我这个错误:“ TypeError:无法设置未定义的属性'0'。”

This occurs when the array is undefined, but I've already defined it in my constructor. 当数组未定义时会发生这种情况,但是我已经在构造函数中定义了它。

  1. parsedData looks like parsedData看起来像
[
    {
      "studyID": "12345",
      "date": "Thu Jul 18 2019 16:05:58 GMT-0700",
      "sex": "f",
      "dateOfBirth": "1987-01-02",
      "minHz": "25.0",
      "maxHz": "55.0",
      "session": [ 
        {
          "incr": "33.2",
          "decr": "34.7"
        },
        {
          "incr": "34.0",
          "decr": "30.8"
        }
      ],
      "average": "31.5",
      "variance": "2.3"
    },

but has been stringified and parsed into an object. 但已被字符串化并解析为一个对象。

  1. I have an array called dateObjects which should store dates. 我有一个名为dateObjects的数组,应该存储日期。 For example, new Date('Thu Jul 18 2019 16:05:58 GMT-0700') would be at index 0. This occurs in the iteration. 例如,新的Date('Thu Jul 18 2019 16:05:58 GMT-0700')将位于索引0。这发生在迭代中。
for (var i = 0; i < this.parsedData.length; i++) {
        this.dateObjects[i] = new Date(this.parsedData[i].date);
    }
  1. My HTML code: 我的HTML代码:
 <div class="table" *ngFor="let data of parsedData; index as i"> 
Date: {{ this.dateObjects[i] | date:'fullDate'}}
</div>

I expect it to print out the dates from the dateObjects array, but it results in an error: TypeError: Cannot set property '0' of undefined. 我希望它可以打印出dateObjects数组中的日期,但是会导致错误:TypeError:无法设置未定义的属性“ 0”。

Because you are already iterating over parsedData and storing them in array (dataObjects), I think instead of parsedData you should be iterating over dataObjects in HTML 因为您已经在parsedData上进行迭代并将其存储在数组(dataObjects)中,所以我认为应该在HTML中对dataObjects进行迭代,而不是parsedData

<div class="table" *ngFor="let data of this.dataObjects; index as i"> 
Date: {{ data | date:'fullDate'}} // here data will be your each array element
</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM