获取对象的唯一标识符

时间:2015-01-17 04:16:00

标签: javascript

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

我在那里尝试将它们与某个ID系统连接起来,所以我知道哪些对象会连接到哪些对象以便稍后查找相关的路径。

例如,这是我想要做的事情的想法:

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

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

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

2 个答案:

答案 0 :(得分:0)

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]);

答案 1 :(得分:0)

在下面的代码中,构造函数可以访问两个私有变量: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);