我有点困在这里,因为我不知道为什么这不起作用。当我尝试运行代码时,它说"ReferenceError: item is not defined"-但我想通过写"let item"我在定义它。你知道这里有什么问题吗?
- 我知道代码看起来比必要的更复杂,但我需要这样做。
class Graph {
constructor() {
this.nodes = new Set();
this.edges = new Set();
}
add(m,n){
let e = new Edge (m,n)
var allEdges = new Set();
for (let item of this.edges){
allEdges.add(item.startpoint.nodeName,item.endpoint.nodeName)
};
if (allEdges.has(e.startpoint.nodeName,e.endpoint.nodeName)){
console.log("first OCL Constraint")
} else if(allEdges.has(e.endpoint.nodeName,e.startpoint.nodeName){
console.log("second OCL Constraint")}
else {
this.edges.add(item.startpoint.nodeName,item.endpoint.nodeName)};
}
};
class Edge {
constructor(startpoint,endpoint) {
this.startpoint = startpoint;
this.endpoint = endpoint;
}
};
class Node {
constructor(nodeName) {
this.nodeName = nodeName
}
};
node1 = new Node (1);
node2 = new Node (2);
node3 = new Node (3);
node4 = new Node (4);
node5 = new Node (5);
myTestGraph = new Graph();
myTestGraph.add(node1,node2);
myTestGraph.add(node2,node1);
myTestGraph.add(node3,node4);
Thanks in advance:)
问题似乎在最后的"else",你引用的"项目"超出其作用域(在for块中声明let item)我认为add()方法的正确代码是:
add(m,n){
let item;
let e = new Edge(m,n);
var allEdges = new Set();
for (item of this.edges){allEdges.add(item.startpoint.nodeName,item.endpoint.nodeName)};
if (allEdges.has(e.startpoint.nodeName,e.endpoint.nodeName)){console.log("first OCL Constraint")}
else if(allEdges.has(e.endpoint.nodeName,e.startpoint.nodeName)){console.log("second OCL Constraint")}
else {this.edges.add(item.startpoint.nodeName,item.endpoint.nodeName)};
}