我有一個對象數組,我需要指定唯一的id。爲簡單起見,我宣佈這個ID的全局變量,我在每一個新的對象更新:將全局變量的值賦值給對象
var id_unit = 0,
units = [],
merc = [
{name: 'grunt', id: 0, level: 1, hp: 1, atk: 1, def: 1, deployed: false},
{name: 'big grunt', id: 0, level: 1, hp: 1, atk: 1, def: 1, deployed: false}
];
function buy_unit(type, callback) {
var unit = merc[type];
unit.id = id_unit;//0 + id_unit //new Number(id_unit) //Number(id_unit)
id_unit = id_unit + 1;
units.push(unit);
callback('OK');
}
問題是,當我使用這個功能,ID似乎變得UNIT_ID的ADRESS而不是它值:
buy_unit
unit_id: 0
i: 0 id: 0 level: 1 deployed: false
buy_unit
unit_id: 1
i: 0 id: 1 level: 1 deployed: false
i: 1 id: 1 level: 1 deployed: false
當我所期待的是:
buy_unit
unit_id: 1
i: 0 id: 0 level: 1 deployed: false
i: 1 id: 1 level: 1 deployed: false
爲什麼UNIT_ID返回它的指針,而不是它的價值?我如何獲得價值?
是一個循環中真正的代碼,使'id_unit'是在閉合捕捉?見http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example – RichieHindle