简体   繁体   中英

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 : Unexpected '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'.

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).

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

I use Microsoft Visual Studio 2012 and 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?

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):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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