Javascript 将全局变量的值赋给对象
我有一个对象数组,其中我需要分配唯一的id。为了简单起见,我为这个id声明了一个全局变量,在每个新对象上更新:Javascript 将全局变量的值赋给对象,javascript,node.js,Javascript,Node.js,我有一个对象数组,其中我需要分配唯一的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, de
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');
}
var unit = Object.create( merc[type] );
问题是,当我使用这个函数时,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]作为新对象的原型:
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');
}
var unit = Object.create( merc[type] );
真正的代码是否在一个循环中,以便在闭包中捕获id_单元?谢谢你,这正是我需要的: