我有一个对象数组,我需要在其中分配唯一的 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的地址而不是它的值:
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返回它的指针而不是它的值?我怎样才能得到这个值?
最佳答案
这不会创建对象的副本:
var unit = merc[type];
它只是使 unit
引用与 merc[type]
相同的对象,因此,如果您分配给 unit.id
您正在更改merc
数组中单元的 id
属性。
您似乎想使用 merc[type]
作为新对象的原型(prototype):
var unit = Object.create( merc[type] );
关于javascript - 将全局变量的值赋给对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30730371/