简体   繁体   English

角度4无法推送未定义的数组

[英]angular 4 not able to push on an array of undefined

I am trying to push on an array for every interval but for some reason I get an error either it is ERROR TypeError: Cannot set property 'NaN' of undefined if I use this.numbers[this.value] = this.value; 我正在尝试为每个时间间隔推送一个数组,但是由于某种原因,我会收到一个错误,或者是ERROR TypeError: Cannot set property 'NaN' of undefined如果使用this.numbers[this.value] = this.value;ERROR TypeError: Cannot set property 'NaN' of undefined this.numbers[this.value] = this.value; or it is core.es5.js:1020 ERROR TypeError: Cannot read property 'push' of undefined if I use this.numbers.push(this.value); 还是core.es5.js:1020 ERROR TypeError: Cannot read property 'push' of undefined如果我使用this.numbers.push(this.value);core.es5.js:1020 ERROR TypeError: Cannot read property 'push' of undefined this.numbers.push(this.value);

here is my code 这是我的代码

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-game-control',
  templateUrl: './game-control.component.html',
  styleUrls: ['./game-control.component.css']
})
export class GameControlComponent implements OnInit {
  timer = null;
  value: number;
  interval: number;
  numbers = [];


  constructor() { }


  ngOnInit() {
      console.log(this.numbers);
  }

  onClickStart() {
    console.log('timer called');
    if (this.timer !== null) {
      return;
    }
    this.timer = setInterval(function() {
      this.value += 1;
      // console.log(this.numbers[this.value - 1 ]);
      // this.numbers[this.value] = this.value;
      this.numbers.push(this.value);
      console.log(this.numbers);
    }, this.interval );
  }

  onClickStop() {
    clearInterval(this.timer);
    this.timer = null;
  }

}

My html is 我的HTML是

<div class="row">
          <div class="col-xs-12 "> 
            <button type="submit" class="btn btn-success" (click)="onClickStart()">Start</button>
            <button type="button" class="btn btn-danger" (click)="onClickStop()">Stop</button>
            <button type="button" class="btn btn-primary" >Clear</button>
          </div>
</div>
<div class="row">
  <div class="col-xs-10">

  <hr>
  <ul class="list-group">
    <a 
      class="list-group-item" 
      style="cursor: pointer"
      *ngFor="let number of numbers"
      >
      <app-even [num]="number" ></app-even>
      <app-odd [num]="number" ></app-odd> 
    </a>
  </ul>
  </div>
</div>

but I don't think it matters yet 但我认为这并不重要

function () {}导致this不指向当前类实例了,因为大多数从其他语言所期望的,用箭头的功能而不是获得所需的行为:

this.timer = setInterval(() => {

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

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