获取对象的唯一标识符

Get a unique identifier of an object

本文关键字:标识符 唯一 取对象 获取      更新时间:2023-09-26

所以我正在尝试设置一个包含路径节点的对象列表。这些途径可以连接到其他途径。

我在那里尝试将它们与一些 ID 系统链接起来,以便我知道哪些对象连接到哪些对象以进行稍后的路径查找相关内容。

例如,这就是

我正在尝试做的事情的想法:

var object = {}; //hypothetical id of 1
    object.connectsTo = [2];
var object2 = {}// hypothetical id of 2
    object2.connectsTo = [1];

这样,我可以在以后需要的时候通过id调用对象。如果这不是 javascript 中的一个选项 - 最好的解决方案是什么?

在下面的代码中,构造函数可以访问两个私有变量:counterdb 。变量 counter 用于创建自动递增的 id,db用于存储对生成对象的引用以供以后检索。

Node

var Node = (function() {
    var counter = 0;
    var db = {};
    // the Node constructor
    var _Node = function(x, y) {
        this.x = x;
        this.y = y;
        this.id = counter++; // use the next available id
        db[this.id] = this; // store a reference to the node for retrieval
        this.connections = {}; // initialize the hashmap of connecting nodes
    };
    // looking up nodes by id
    _Node.getNodeById = function(id) {
        return db[id];
    };
    // some utility methods
    // what exactly you want to do with this?
    // not sure what methods you'd need
    _Node.prototype.connectTo = function(node) {
        this.connections[node.id] = true;
    };
    _Node.prototype.disconnectFrom = function(node) {
        delete this.connections[node.id];
    };
    _Node.prototype.isConnectedTo = function(node) {
        return !!this.connections[node.id];
    };
    _Node.prototype.getConnectingNodes = function () {
        var connectingNodes = [];
        var keys = Object.keys(this.connections);
        for(var i = 0; i < keys.length; i++) {
            connectingNodes.push(db[this.connections[keys[i]]]);
        }
        return connectingNodes;
    };
    _Node.prototype.distanceTo = function(node) {
        return Math.sqrt(
            Math.pow(node.y - this.y, 2) + 
            Math.pow(node.x - this.x, 2)
        );
    };
    _Node.prototype.findShortestPathTo = function(node) {
        // path finding logic goes here
    };
    return _Node;
}());

示例用法

var pointA = new Node(0, 0);
var pointB = new Node(0, 4);
var pointC = new Node(0, 5);
var pointD = new Node(4, 5);
var pointE = new Node(4, 4);
var pointF = new Node(4, 2);
var path = pointA.findShortestPathTo(pointF);
function node(nodeId, connectsTo) {
    this.nodeId = nodeId; // Type int
    this.connectsTo = connectsTo; // connectsTo should be an Array()
}
var node1 = new node(1, [0, 3, 4]);