MMTTMM
2023-09-28 17:31:59
我有這兩門課:class Node { constructor(nodeId){ this.nodeId = nodeId; this.adjacencies = []; } connectToNode(nodeToConnectTo){ this.adjacencies.push(nodeToConnectTo); }}class Graph{ constructor(nodes){ this.nodes = nodes; } printGraph(){ for (let node in this.nodes){ console.log(node.nodeId); } }}我只是想通過這種方式調用printGraph打印所有nodeIds :let node1 = new Node('1');let node2 = new Node('2');let node3 = new Node('3');const arr = [node1, node2, node3];let graph = new Graph(arr);graph.printGraph();但它正在打印undefined。我似乎無法弄清楚為什么它不簡單地打印nodeId.
4 回答

尚方寶劍之說
TA貢獻1788條經驗 獲得超4個贊
您使用了錯誤的 for 循環。嘗試將其更改為:
printGraph(){
for (let node of this.nodes){
console.log(node.nodeId);
}
}
for..of 循環應該按照您想要的方式循環遍歷節點。
結果:
1
2
3

慕哥9229398
TA貢獻1877條經驗 獲得超6個贊
看來您正在使用關鍵字迭代數組對象的屬性in。對于數組,這意味著您要迭代索引(鍵),即 3 成員數組中的 0、1、2。這些是字符串,沒有屬性nodeId,所以你的輸出是undefined. console.log(node, typeof node)如果您在當前循環內運行(與 保持一致),您將看到這些in。
如果在 for 循環中使用of關鍵字,您將獲得數組的值,即值為 1、2 和 3 的對象nodeId。因此,您所要做的就是更改in為of,您將獲得所需的輸出。
就我個人而言,我會用這個:
printGraph(){
const nodeIds = this.nodes.map(node => node.nodeId);
console.log(nodeIds);
}

藍山帝景
TA貢獻1843條經驗 獲得超7個贊
你需要打印,console.log(node);
因為你正在循環槽let node in this.nodes
node
實際節點來自哪里this.nodes
添加回答
舉報
0/150
提交
取消