I have these two classes:
JavaScript
x
24
24
1
class Node {
2
constructor(nodeId){
3
this.nodeId = nodeId;
4
this.adjacencies = [];
5
}
6
7
connectToNode(nodeToConnectTo){
8
this.adjacencies.push(nodeToConnectTo);
9
}
10
}
11
12
class Graph{
13
constructor(nodes){
14
this.nodes = nodes;
15
}
16
17
printGraph(){
18
for (let node in this.nodes){
19
console.log(node.nodeId);
20
}
21
22
}
23
}
24
I’m simply trying to call printGraph
to print all the nodeId
s this way:
JavaScript
1
8
1
let node1 = new Node('1');
2
let node2 = new Node('2');
3
let node3 = new Node('3');
4
const arr = [node1, node2, node3];
5
let graph = new Graph(arr);
6
7
graph.printGraph();
8
But it’s printing undefined
. I can’t seem to figure out why it isn’t simply printing the nodeId
.
Advertisement
Answer
you are using the wrong for loop. Try changing it to:
JavaScript
1
6
1
printGraph(){
2
for (let node of this.nodes){
3
console.log(node.nodeId);
4
}
5
}
6
A for..of loop should loop over the node the way you want.
Result:
JavaScript
1
4
1
1
2
2
3
3
4