javascript - 将全局变量的值赋给对象

标签 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, 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/

相关文章:

javascript - 从已编译的 CSS 中删除所有注释 - Grunt

javascript - 删除或隐藏使用 JavaScript 的存储过程填充的下拉列表中的某些值?

javascript - 在谷歌图表AngularJS中添加行

javascript - 在 Electron 中获取渲染器进程 ID

node.js - Mongoose Pre Command 未按预期工作

javascript - 如何使用 “JavaScript enabled” 获取 HTML?

javascript - 如何在 Node 模块和另一个 JavaScript 文件中声明数组 (Mongodb)

javascript - 多人倒计时器

node.js - 将不同的域指向单个 EC2 实例上的不同 Docker 容器?

javascript - $(document).bind ('ready' , function) 和 $(document).ready(function() {}) 有什么区别