获取对象的唯一标识符
Get a unique identifier of an object
所以我正在尝试设置一个包含路径节点的对象列表。这些途径可以连接到其他途径。
我在那里尝试将它们与一些 ID 系统链接起来,以便我知道哪些对象连接到哪些对象以进行稍后的路径查找相关内容。
例如,这就是我正在尝试做的事情的想法:
var object = {}; //hypothetical id of 1
object.connectsTo = [2];
var object2 = {}// hypothetical id of 2
object2.connectsTo = [1];
这样,我可以在以后需要的时候通过id调用对象。如果这不是 javascript 中的一个选项 - 最好的解决方案是什么?
在下面的代码中,构造函数可以访问两个私有变量:counter
和 db
。变量 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]);
相关文章:
- 三星智能电视唯一的设备标识符
- JavaScript:将 URL 字符串转换为唯一标识符
- 在Chart.js段中嵌入唯一标识符
- 如何重新编码我的jQuery/JavaScript函数,使其更通用,不需要唯一标识符
- Facebook 连接唯一的秘密用户标识符
- 获取对象的唯一标识符
- 在 JavaScript 中创建唯一标识符
- 有没有办法获取谷歌浏览器实例的唯一标识符
- 永久唯一移动设备标识符(Evercookie?)
- chase.com 登录流是否使用 JavaScript 中的设备唯一标识符
- 使用1个HTML表单:要求用户提供唯一标识符,从数据库中获取记录,解析为JSON,使用jquery填充插件填充HTML页
- AJAX 响应消息唯一标识符
- Phonegap和Angularjs-iOS唯一标识符
- 使用微时间作为唯一标识符的潜力
- Jquery . AJAX():唯一的AJAX查询标识符
- 在JavaScript中生成一个(非udid)标识符来唯一标识iOS设备
- 如何将元素个性化为唯一标识符
- Javascript根据唯一标识符替换十六进制
- 如何用IP地址和其他标识符唯一地识别访问者
- 使用key属性作为唯一标识符