将全局变量的值赋给对象

时间:2021-02-12 21:20:58

I have a array of object, in which I need to assign unique id. To make it simple, I declared a global var for this id, that I update at every new object:

我有一个对象数组,在数组中我需要分配唯一的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');
}

Problem is, when I use this function, id seems to have got the adress of unit_id instead of its value:

问题是,当我使用这个函数时,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

When what I was expecting was:

当我期待的是:

buy_unit
unit_id: 1
i: 0    id: 0   level: 1        deployed: false
i: 1    id: 1   level: 1        deployed: false

Why is unit_id returning its pointer and not its value? How can I get the value?

为什么unit_id返回它的指针而不是它的值?我怎样才能得到这个值?

1 个解决方案

#1


4  

This doesn't create a copy of the object:

这不会创建对象的副本:

var unit = merc[type];

It just makes unit refer to the same object as merc[type], so if you assign to unit.id you are changing the id property of a unit in your merc array.

它只是使unit指向与merc[type]相同的对象,所以如果你分配给unit。id您正在更改merc数组中的一个单元的id属性。

It seems like you want to use your merc[type] as the prototype for a new object:

似乎你想用你的merc[type]作为一个新对象的原型:

var unit = Object.create( merc[type] );

#1


4  

This doesn't create a copy of the object:

这不会创建对象的副本:

var unit = merc[type];

It just makes unit refer to the same object as merc[type], so if you assign to unit.id you are changing the id property of a unit in your merc array.

它只是使unit指向与merc[type]相同的对象,所以如果你分配给unit。id您正在更改merc数组中的一个单元的id属性。

It seems like you want to use your merc[type] as the prototype for a new object:

似乎你想用你的merc[type]作为一个新对象的原型:

var unit = Object.create( merc[type] );