有什么更好的方法来执行此代码?
在游戏开始时,我为所有新游戏信息声明了一个变量。
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 :(得分:2)
不是拼接数组来清空它,只需将其长度减少到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}}
答案 1 :(得分:2)
if
s 代码
var initGameInfo = function () {
return {
players: [],
playersList: [],
enemies: [],
enemiesList: [],
drops: [],
dropsList: [],
attacks: [],
attacksList: [],
LVL: null
}
},
newGameInfo = initGameInfo();
// game code
//reset it
newGameInfo = initGameInfo();
答案 2 :(得分:0)
最简单的解决方案是将初始化放在一个函数中,并在游戏开始和重置时分配返回的值。
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);