[英]angular 4 not able to push on an array of undefined
我正在嘗試為每個時間間隔推送一個數組,但是由於某種原因,我會收到一個錯誤,或者是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;
還是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);
這是我的代碼
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;
}
}
我的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>
但我認為這並不重要
function () {}
導致this
不指向當前類實例了,因為大多數從其他語言所期望的,用箭頭的功能而不是獲得所需的行為:
this.timer = setInterval(() => {
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.