如何以JSLint方式迭代关联数组并删除一些元素(JavaScript, node.js 4.2.3)

How to iterate associative array and delete some elements in JSLint way (JavaScript, node.js 4.2.3)

我写了代码:

for (var game in this.currentGames) {
    if (this.currentGames[game].gameState === consts.GS_GAME_DELETE) {
        delete this.currentGames[game];
    }
}

它工作正常,但 JSLint.net 显示警告:

JSLint:意外 'var'。

当我尝试修复它时:

var game;
for (game in this.currentGames) {
    if (this.currentGames[game].gameState === consts.GS_GAME_DELETE) {
        delete this.currentGames[game];
    }
}

我收到这样的警告: JSLint :预期 'Object.keys' 而不是看到 'for in'.

我尝试修复并编写了下一个代码:

Object.keys(this.currentGames).forEach(function (item, i, arr) {
    if (arr[i].gameState === consts.GS_GAME_DELETE) {
        delete arr[i];
    }
});

它只是行不通,因为 arr 是数组(不是关联数组)。

当我尝试:

Object.keys(this.currentGames).forEach(function (item) {
    if (this.currentGames[item].gameState === consts.GS_GAME_DELETE) {
        delete this.currentGames[item];
    }
});

我得到 运行-时间错误:

if (this.currentGames[item].gameState === consts.GS_GAME_DELETE) {
        ^

TypeError: 无法读取未定义的 属性 'currentGames'

我使用 Microsoft Visual Studio 2012 和 JSLint.NET。

所以,我的问题是:在循环中从关联数组中删除元素的正确方法在哪里?或者有什么方法可以关闭 JSLint?

for (var game in this.currentGames) {
  if (this.currentGames.hasOwnProperty(game)
    && this.currentGames[game].gameState === consts.GS_GAME_DELETE
  ) {
    delete this.currentGames[game];
  }
}

您也可以通过在匿名函数范围(具有自己的 this 上下文)之外定义一些具有 this 值的变量来使用您的最后一个变体:

var self = this;
Object.keys(this.currentGames).forEach(function (item) {
  if (self.currentGames[item].gameState === consts.GS_GAME_DELETE) {
    delete self.currentGames[item];
  }
});