二维对象/关联数组到三维对象Javascript

时间:2012-05-14 18:33:18

标签: javascript arrays object associative-array

无论如何都要去形成这个

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++;
}

1 个答案:

答案 0 :(得分: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.