我正在尝试学习图数据结构,并通过控制台当前数据发现了这种奇怪的行为,我的主要代码如下
class Graph {
constructor() {
this.adjacencyList = {};
}
addVertex(vertex) {
if (!this.adjacencyList[vertex]) this.adjacencyList[vertex] = [];
}
addEdge(v1, v2) {
this.adjacencyList[v1].push(v2);
this.adjacencyList[v2].push(v1);
}
removeEdge(v1, v2) {
this.adjacencyList[v1] = this.adjacencyList[v1].filter((el) => el !== v2);
this.adjacencyList[v2] = this.adjacencyList[v2].filter((el) => el !== v1);
}
}
我的控制台日志是
let graph = new Graph();
graph.addVertex("tokyo");
graph.addVertex("dallas");
graph.addVertex("aspen");
graph.addEdge("tokyo", "dallas");
graph.addEdge("dallas", "aspen");
console.log(graph.adjacencyList);
graph.removeEdge("dallas", "tokyo");
console.log(graph.adjacencyList);
我通常期望的是删除之前的第一个console.log应该包含边缘,而之后的console.log将包含删除后的边缘,这就是我在对象中看到的
{东京:数组(1),达拉斯:数组(2),白杨:数组(1)}
{东京:数组(0),达拉斯:数组(1),白杨:数组(1)}
但是当我打开对象时,我没有看到对象 1 中的预期值
aspen: ['dallas']
dallas: ['aspen']
Tokyo: []
这与 console.log 中的第二个对象完全相同
在记录对象之前,创建它的克隆:
structuredClone(graph.adjacencyList)
这样,在记录相邻的“列表”时,引用就是一个新对象。
class Graph {
constructor() {
this.adjacencyList = {};
}
addVertex(vertex) {
if (!this.adjacencyList[vertex]) this.adjacencyList[vertex] = [];
}
addEdge(v1, v2) {
this.adjacencyList[v1].push(v2);
this.adjacencyList[v2].push(v1);
}
removeEdge(v1, v2) {
this.adjacencyList[v1] = this.adjacencyList[v1].filter((el) => el !== v2);
this.adjacencyList[v2] = this.adjacencyList[v2].filter((el) => el !== v1);
}
}
let graph = new Graph();
graph.addVertex("tokyo");
graph.addVertex("dallas");
graph.addVertex("aspen");
graph.addEdge("tokyo", "dallas");
graph.addEdge("dallas", "aspen");
console.log(structuredClone(graph.adjacencyList));
graph.removeEdge("dallas", "tokyo");
console.log(structuredClone(graph.adjacencyList));
.as-console-wrapper { top: 0; max-height: 100% !important; }