簡體   English   中英

清空對象的屬性

[英]Empty an object's properties

什么是執行此代碼的更好方法?

在游戲開始時,我為所有新游戲信息聲明了一個變量。

var newGameInfo = {
   players: [],
   playersList: [],
   enemies: [],
   enemiesList: [],
   drops: [],
   dropsList: [],
   attacks: [],
   attacksList: [],
   LVL: null
}

稍后,我通過此代碼對所有變量清空此變量。

    if(newGameInfo.players.length > 0) newGameInfo.players.splice(0, newGameInfo.players.length);
    if(newGameInfo.playersList.length > 0) newGameInfo.playersList.splice(0, newGameInfo.playersList.length);
    if(newGameInfo.enemies.length > 0) newGameInfo.enemies.splice(0, newGameInfo.enemies.length);
    if(newGameInfo.enemiesList.length > 0) newGameInfo.enemiesList.splice(0, newGameInfo.enemiesList.length);
    if(newGameInfo.drops.length > 0) newGameInfo.drops.splice(0, newGameInfo.drops.length);
    if(newGameInfo.dropsList.length > 0) newGameInfo.dropsList.splice(0, newGameInfo.dropsList.length);
    if(newGameInfo.attacks.length > 0) newGameInfo.attacks.splice(0, newGameInfo.attacks.length);
    if(newGameInfo.attacksList.length > 0) newGameInfo.attacksList.splice(0, newGameInfo.attacksList.length);
    if(newGameInfo.LVL !== null) newGameInfo.LVL = null;

任何建議將不勝感激! :)這段代碼占用了很多空間,可以完成如此​​簡單的任務。

與其拼接數組以清空它,不如將它的長度減小到0,具有相同的效果:

newGameInfo.players.length = 0;

要立即清理整個狀態,請使用以下命令:

Object.keys(newGameInfo).forEach(function(propName) {
  // iterating over properties of `newGameInfo`
  if (Array.isArray(newGameInfo[propName])) {
    // if it's an array, empty it (but do not throw out the object!)
    newGameInfo[propName].length = 0;
  }
  else {
    newGameInfo[propName] = null;
  }
});
  1. 把它放在一個函數中
  2. 如果您覆蓋,誰在乎狀態是什么—擺脫if s
  3. 如果要覆蓋,為什么要拼接? 只是覆蓋。

var initGameInfo = function () {
        return {
            players: [],
            playersList: [],
            enemies: [],
            enemiesList: [],
            drops: [],
            dropsList: [],
            attacks: [],
            attacksList: [],
            LVL: null
        }
    },
    newGameInfo = initGameInfo();

// game code


//reset it
newGameInfo = initGameInfo();

最簡單的解決方案是將初始化放在函數中,並在游戲開始和重置時分配返回的值。

function init() {
  return {
    players: [],
    playersList: [],
    enemies: [],
    enemiesList: [],
    drops: [],
    dropsList: [],
    attacks: [],
    attacksList: [],
    LVL: null
  }
}

var newGameInfo = init();
console.log('Logging game info');
console.log(newGameInfo);

console.log('playing the game...');
newGameInfo.LVL = 1;
newGameInfo.players.push('player 1');
newGameInfo.enemies.push('easy enemy');

console.log('Logging game info again');
console.log(newGameInfo);

console.log('Resetting');
newGameInfo = init();

console.log('Logging game info');
console.log(newGameInfo);

暫無
暫無

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

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