简体   繁体   English

如何迭代关联数组并以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)

I wrote code: 我写了代码:

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

It works fine, but JSLint.net show me warning: 它工作正常,但JSLint.net告诉我警告:

JSLint : Unexpected 'var'. JSLint:意外的'var'。

When I tried to fix it: 当我试图解决它:

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

I get such warning: JSLint : Expected 'Object.keys' and instead saw 'for in'. 我得到了这样的警告:JSLint:预期'Object.keys'而是看到'for in'。

I tried to fix and wrote next code: 我试图修复并编写下一个代码:

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

It just not works, because arr is array (not associative array). 它只是不起作用,因为arr是数组(不是关联数组)。

When I try to: 当我尝试:

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

I get run-time error: 我得到运行时错误:

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

TypeError: Cannot read property 'currentGames' of undefined TypeError:无法读取未定义的属性“currentGames”

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

So, my question is: is where right way for deleting element from associative array in cycle? 所以,我的问题是:在循环中从关联数组中删除元素的正确方法是什么? Or is where way to shut JSLint up? 或者是关闭JSLint的方法?

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

You also may use your last variant by define some variable with this value out of anonymous function scope (which has its own this context): 你也可以用你的最后变种通过定义一些变量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];
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM