【问题标题】:How to iterate associative array and delete some elements in JSLint way (JavaScript, node.js 4.2.3)如何以 JSLint 方式迭代关联数组并删除一些元素(JavaScript,node.js 4.2.3)
【发布时间】:2026-01-29 01:30:02
【问题描述】:

我写了代码:

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

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

JSLint:意外的“变量”。

当我试图修复它时:

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?

【问题讨论】:

    标签: javascript node.js jslint


    【解决方案1】:
    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];
      }
    });
    

    【讨论】:

    • 您的第一个变体会生成相同的警告:JSLint : Unexpected 'var'。第二个变体可以在没有警告的情况下工作,但为什么我应该这样做呢?我认为,这是丑陋的旧语法(我的意思是,使用“自我”)。
    • 用第二个,绝对正常。根据需要重命名 self 变量。
    • 如我所见,JSLint 不允许在没有相应容忍选项的情况下使用 for 循环,但总共不允许使用 for-in 循环。
    • 感谢您的帮助。我认为,关于 JSLint 生成此类警告的原因以及哪种方法更快、更具可读性的讨论超出了我的问题范围。