簡體   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)

我寫了代碼:

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];
  }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM