我开始玩我的内存游戏,但开始后就停止了:( For
循环对我不起作用。
我的代码:
const game = {
...
shuffledCards: [],
startGame: () => {
...
// clear variables
this.shuffledCards = [];
for (let i = 0; i < this.cardsCount; i++) {
this.shuffledCards.push(Math.floor(i/2));
}
}
}
我想生成一个看起来像这样的数组[0, 0, 1, 1, 2, 2...]
,但是 for
循环返回一个空数组。你知道为什么吗?当我尝试将变量从 this
更改为普通变量并将代码粘贴到浏览器中时,它起作用了......
最佳答案
箭头函数不继承this
。您需要将代码重写为
const game = {
...
startGame() {
...
this....
}
...
}
关于javascript - For 循环在对象的方法中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48853814/