gpt4 book ai didi

javascript - Angular 4无法推送未定义的数组

转载 作者:行者123 更新时间:2023-11-28 14:48:29 24 4
gpt4 key购买 nike

我试图在每个间隔推送一个数组,但由于某种原因,我收到一个错误,要么是 ERROR TypeError: Cannot set property 'NaN' of undefined 如果我使用 this .nu​​mbers[this.value] = 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(() => {

关于javascript - Angular 4无法推送未定义的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45488008/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com