2012-05-14 161 views
0

反正是有去形成這個二維對象/關聯數組成三維對象中的JavaScript

var stateDat = { 
ME: ['Maine',1328361], 
etc. 
}; 

對此

var stateDatHistory = { 
1:[ 
    ME: ['Maine',1328361], 
    etc. 
    ], 
2:[ 
    ME: ['Maine',1328361], 
    etc. 
    ], 
etc 
}; 

動態的功能?例如,這不起作用...

turn = 1; 

function start(){ 
stateDatHistory[turn].push(stateDat); 
stateDat['ME'][1]= stateDat['ME'][1] - 500; //changing population 
turn++; 
} 
+0

數組文字不能有'ME:'裏面 –

回答

1

它的歷史部分可能是一個對象數組。所以......

var stateDatHistory = [ 
    { ME: ['Maine', 1328361] } 
]; 

或者,如果你需要通過一鍵引用歷史上每一個「一步」,也可能是包含數組值對象的對象...

var stateDatHistory = { 
    1: [ 
     { ME: ['Maine', 12334] } 
    ] 
} 

在後一種情況下,「開始」碼會是這樣的......

turn = 1 

function start() { 
    if (typeof stateDatHistory[turn] === 'undefined') { 
     stateDatHistory[turn] = []; 
    } 
    stateDatHistory[turn].push(stateDat); 
    stateDat['ME'][1]= stateDat['ME'][1] - 500; //changing population 
    turn++; 
} 

說了這麼多,我覺得傾向於提的是使用對象包含所有這種狀態的數據將是一個很好的決定。考慮例如...

// Define our manager 
var stateDatManager = function() { }; 
(function(instance) { 

    instance.init = function() { 
     // Setup internal state 
     this.history = {}; 
     this.turn = 0; 
     this.initialized = true; 
    }; 

    instance.start = function(turn, data) { 
     if (!this.initialized) { this.init(); } 
     this.turn = turn; 
     this.addToHistory(data); 
    }; 

    instance.addToHistory(data) { 
     if (typeof this.history[this.turn] === 'undefined') { 
      this.history[this.turn] = []; 
     } 
     this.history[this.turn].push(data); 
    }; 

    instance.advanceTurn() { 
     this.turn += 1; 
    }; 

}(stateDatManager.prototype)); 

// Use it 
var manager = new stateDatManager(); 
manager.start(1, [ 
    { ME: ['Maine', 1328361] } 
]); 

// Move to the next turn... 
manager.advanceTurn(); 

// etc.