javascript - 如何为对象实例生成唯一 ID?

标签 javascript arrays javascript-objects

我正在构建一个简单的视频游戏,我正在尝试找到从玩家库存数组中删除对象的最佳方法。

我想为每个游戏项目使用一个 ID,但我不确定如何生成这些 ID。

显然,手动为每个实例提供唯一的 ID 效率不高。

我想我可以在构造函数原型(prototype)上添加一个属性,或者直接在构造函数本身上添加一个属性,称为“生成”,该属性随着从中创建的每个实例而增加 1,然后让每个实例返回并使用它作为其 ID 。

或者,我可以在创建每个对象时随机生成一个随机数,但即使数量很大,您可能拥有多个具有相同 ID 的对象的风险也非常小。

如何为每个对象实例添加唯一 ID?

  function Item(name,weight,value,description,type){
        this.name=name;
        this.weight = weight;
        this.value=value;
        this.description=description;
        this.type=type;
        this.id= this.generated;/*"this" here obviously means the a property immediately on the object its self on not something further up the chain*/

        this.generated+=1;
     }
    Item.prototype.generated=0;

  function Item(name,weight,value,description,type){
        this.name=name;
        this.weight = weight;
        this.value=value;
        this.description=description;
        this.type=type;
        this.id= this.__proto__.constructor.generated;/* this doesnt work either I'm assuming maybe because the constructor and __proto__ properties are added after everything in the constructor function runs, so its undefined?*/

        this.__proto__.constructor.generated+=1;
     }
     Item.generated=0;

最佳答案

使用带有计数器的闭包,每次创建对象时计数器都会递增:

var item=(function(){
var id=0;
return function(name,...){
this.name=name
...
this.id=id;
++id; 
}
})()
//to remove an object use Array.splice()

关于javascript - 如何为对象实例生成唯一 ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46050664/

相关文章:

javascript - 我可以在不使用 javascript 的情况下开始这个简单的 CSS 转换吗

php - 将 3d 数组转换为唯一值的关联数组并对它们的相关值求和

JavaScript 对象文字 - 数据操作

javascript - 带有分层字段的 HTML 表单到 JSON 对象

javascript - JS中对象的频率排序数组,如果频率匹配则根据对象属性排序

node.js - 将嵌套对象链表转换为数组 Node js

javascript - 使用 angularJS 在表中禁用行向上/向下移动的第一列

php - 使用 PHP 和 Javascript 的 HTML 图像映射/用户可以选择颜色

javascript - 为什么带有 show/hide 的 for 循环在 Vue JS 中不起作用?

c++ - 将数组的次对角线上的元素相乘。宝兰C