首页 > 解决方案 > 为什么这个 (gameindex) 属性值在由 console.log 打印时未定义?

问题描述

在代码中 console.log(this.gameIndex) 打印出 undefined。为什么是这样?当我在构造函数中使用 console.log(this.gameIndex) 时,会打印出正确的值。

打字稿

export class HomeComponent implements OnInit {
  game:String;
  gameIndex;
  games:String[];
  constructor() { 
    this.gameIndex = 0;

    this.games = ['game1','game2','game3'];
    this.game = this.games[this.gameIndex];

    setInterval(this.rotatingBackground,3000);
    console.log(this.gameIndex);
  }

  ngOnInit() {


  }

  rotatingBackground():any {
    console.log(this.gameIndex);
    this.game = this.games[this.gameIndex];
    console.log(this.game);
  }


}

标签: angulartypescript

解决方案


那是因为你没有定义它。

gameIndex;

应该

gameIndex:Number;`

推荐阅读