【问题标题】:For loop not working in an object's methodFor循环在对象的方法中不起作用
【发布时间】:2018-02-18 16:16:54
【问题描述】:

我开始制作我的记忆迷你游戏,但在开始后立即停止:(For 循环不适合我。 我的代码:

const game = {
   ...
   shuffledCards: [],

   startGame: () => {
    ...
     // clear variables
     this.shuffledCards = [];

     for (let i = 0; i < this.cardsCount; i++) {
        this.shuffledCards.push(Math.floor(i/2));
     }
   }
}

我想生成一个看起来像 this[0, 0, 1, 1, 2, 2...] 的数组,但是 for 循环返回一个空数组。你知道为什么吗?当我尝试将变量从this 更改为普通变量并将代码粘贴到浏览器中时,它可以工作...

【问题讨论】:

标签: javascript arrays loops object for-loop


【解决方案1】:

箭头函数不继承this。您需要将代码重写为

const game = {
   ...
   startGame() {
     ...
     this....
   }
   ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-21
    • 2021-04-26
    • 2019-04-27
    • 2017-06-22
    • 2021-09-07
    • 2013-11-14
    • 2022-06-17
    相关资源
    最近更新 更多