JavaScript使用字符串值作为对对象的引用(不使用eval())

Kodekan

我创建了一堆具有“名称”,“类型”,“ positionX”,“ positionY”等属性的对象(节点)。它们还具有以空开头的数组“连接”。创建对象时,我还将其存储在Array objectList中,因此可以轻松地在循环中遍历它们。

//Pseudo-Object
function Node (n,t,x,y) {
    this.name = n;
    this.type = t;
    this.connections = new Array();
    this.positionX = 0;
    this.positionY = 0;
    tempArrayPosition = nodeList.length;
    nodeList[tempArrayPosition] = this;
}

//Create node list
var nodeList = new Array();

//Create some nodes
var node1 = new Node("node.foo", "io", 40, 60);
var node2 = new Node("node.bar", "fw", 10, 10);
var node3 = new node("node.narf", "mcu", 20, 100);

遍历nodeList数组可以正常工作。例如,我可以使用此代码来显示一个节点对象具有多少个连接:

//Create some connections (will later be done by a method of Node)
node2.connections[node2.connections.length] = "node1";
node2.connections[node2.connections.length] = "node3";
node3.connections[node3.connections.length] = "node2";

console.log("Show number of connections between nodes:");
for (var i = nodeList.length - 1; i >= 0; i--) {
    console.log("Node " + nodeList[i].name + " has " + nodeList[i].connections.length + " connections to other nodes.");
};

现在,当我想详细显示连接时,问题就开始了。.connections数组由变量/对象名称的字符串组成。但是我似乎无法使用它们来访问那些对象。

我这样扩展循环:

console.log("Show number of connections between nodes:");
for (var i = nodeList.length - 1; i >= 0; i--) {
    console.log("Node " + nodeList[i].name + " has " + nodeList[i].connections.length + " connections to other nodes.");
    if (nodeList[i].connections.length > 0) {
        for (var j = nodeList[i].connections.length - 1; j >= 0; j--) {
            var tempObjectName = nodeList[i].connections[j];
            console.log(nodeList[i].name    + " - " + tempObjectName.name);
        }
    }
};

它返回“未定义”-因为很明显它看不到“ node1”等对象引用,而是字符串。我知道我可以用

var tempObjectName = eval(nodeList[i].connections[j]);

但是,即使我很少有JS经验,我仍然看到“ eval()是邪恶的,不要使用它”十几次了……

所以我的问题是:

  • a)是否有一种简单且“安全”(非评估)的方法使JS将数组中的字符串作为对同名var / object的引用?
  • b)我尝试组织/管理我创建的对象(使用对象数组)的方式中是否存在根本缺陷?
  • b.2)如果是这样,哪种方式更优雅?

感谢您的时间。

叶子

您应该存储对象本身而不是其名称:

node2.connections.push(node1);

如果您不喜欢此建议,请尝试以下操作:

var tempObjectName = window[nodeList[i].connections[j]];

将工作如果node1node2nodeN是在全球范围内,这是一个肮脏的做法声明。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章