如何:检索和检查数组中的嵌套对象
How to :Retrieve & check nested Objects in an Array
我有以下问题,过去几天未能解决。
所以我有一个名为“节点”的 class,它有 属性 个邻居 - 这是一个数组。
当我将节点(节点 A)作为“邻居”插入到邻居数组中时,它必须是 Class 邻居的一个实例,它采用 Class 邻居的实例节点B作为“对端节点”作为参数。
现在我必须创建一个语句来检查节点 A 和 B 之间的连接是否已经存在
最好的方法是什么?我遇到了解构的方法,但我不确定它是否适合这项任务。
class Node {
constructor(nodeName) {
this.nodeName = nodeName;
this.neighbours = [];
}
};
class Neighbour {
constructor(oppositeNode, weight = null) {
this.oppositeNode = oppositeNode;
this.weight = weight;
}
};
nodea = new Node(a);
nodeb = new Node(b);
nodea.neighbours.push(new Neighbour(nodeb));
所以我希望能够编写的语句如下:
伪代码
如果(节点A在节点A.neighbours中有节点B){x}
提前致谢
这是您的脚本的延续,使用 find
方法进行检查:
class Node {
constructor(nodeName) {
this.nodeName = nodeName;
this.neighbours = [];
}
};
class Neighbour {
constructor(oppositeNode, weight = null) {
this.oppositeNode = oppositeNode;
this.weight = weight;
}
};
nodea = new Node("a");
nodeb = new Node("b");
nodea.neighbours.push(new Neighbour(nodeb));
let neighbour = nodea.neighbours.find(neighbour => neighbour.oppositeNode == nodeb);
if (neighbour) console.log("found neighbor. It has weight " + neighbour.weight);
else console.log("not found");
我有以下问题,过去几天未能解决。
所以我有一个名为“节点”的 class,它有 属性 个邻居 - 这是一个数组。
当我将节点(节点 A)作为“邻居”插入到邻居数组中时,它必须是 Class 邻居的一个实例,它采用 Class 邻居的实例节点B作为“对端节点”作为参数。
现在我必须创建一个语句来检查节点 A 和 B 之间的连接是否已经存在
最好的方法是什么?我遇到了解构的方法,但我不确定它是否适合这项任务。
class Node {
constructor(nodeName) {
this.nodeName = nodeName;
this.neighbours = [];
}
};
class Neighbour {
constructor(oppositeNode, weight = null) {
this.oppositeNode = oppositeNode;
this.weight = weight;
}
};
nodea = new Node(a);
nodeb = new Node(b);
nodea.neighbours.push(new Neighbour(nodeb));
所以我希望能够编写的语句如下:
伪代码
如果(节点A在节点A.neighbours中有节点B){x}
提前致谢
这是您的脚本的延续,使用 find
方法进行检查:
class Node {
constructor(nodeName) {
this.nodeName = nodeName;
this.neighbours = [];
}
};
class Neighbour {
constructor(oppositeNode, weight = null) {
this.oppositeNode = oppositeNode;
this.weight = weight;
}
};
nodea = new Node("a");
nodeb = new Node("b");
nodea.neighbours.push(new Neighbour(nodeb));
let neighbour = nodea.neighbours.find(neighbour => neighbour.oppositeNode == nodeb);
if (neighbour) console.log("found neighbor. It has weight " + neighbour.weight);
else console.log("not found");