javascript - For 循环在对象的方法中不起作用

标签 javascript arrays loops object for-loop

我开始玩我的内存游戏,但开始后就停止了:( 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/

相关文章:

javascript - html 格式的电子邮件内容

php - 在 codeigniter 中使用 PHP 导出表中的对象数组

php - MySQL - 比较来自 Ajax 数组的值,如果不在表中则删除它们

node.js - 在 Echo Show 上循环播放视频

c - C编程ASCII基本

c - 在 C 中迭代 CSV 文件中的列

javascript - <time> 元素中的日期时间属性

javascript - 将 PartialView 加载到 Bootstrap 模式中,同时传递 ID 值

javascript - 如何在每次打开新选项卡或页面时预加载本地 JavaScript?

php - 将平面数组转换为按类别分组的数组