Pra*_*uri 0 javascript ecmascript-6
我正在学习 JS 中的数据结构,并编写了一些代码来构建图数据结构。
但似乎有一个问题我无法理解为什么会发生。
请查看 getGraph() 方法的注释。我只是在这里打印列表的大小和列表本身。即使列表中有数据,list.size 也会返回 0。
我创建了一个单独的地图,添加了数据并打印了它。有用。但在下面的情况下。
class Graph {
constructor() {
this.list = new Map();
}
addVertex(vertex) {
if (!this.list[vertex]) {
this.list[vertex] = [];
console.log("Added", this.list);
} else {
console.log("Vertex already exists!");
}
}
addEdge(vertex, node) {
if (this.list[vertex]) {
if (!(this.list[vertex].indexOf(node) > -1)) {
this.list[vertex].push(node);
} else {
console.log('Node : ' + node + " already added!"); //?
}
} else {
console.log("Vertex " + vertex + " does not exist!")
}
}
getGraph() {
console.log(this.list);
console.log(this.list.size); // List size comes as zero even if I added some nodes and vertices
}
}
var graph = new Graph();
graph.addVertex("1");
graph.addVertex("2");
graph.addVertex("3");
graph.addVertex("1");
graph.addVertex("5");
graph.addVertex("5");
graph.addEdge("1", "3");
graph.addEdge("2", "3");
graph.addEdge("2", "3");
graph.addEdge("12", "3");
graph.getGraph();
Run Code Online (Sandbox Code Playgroud)
if (!this.list[vertex]) {
this.list[vertex] = [];
Run Code Online (Sandbox Code Playgroud)
这不是与地图内容交互的正确方式。它是合法的 javacript,但您将任意键/值对附加到映射对象,而不是实际将内容存储在映射中。
相反,请执行以下操作:
if (!this.list.has(vertex) {
this.list.set(vertex, []);
}
Run Code Online (Sandbox Code Playgroud)
同样,当你想从地图中获取数据时,不要使用括号语法,使用this.list.get(vertex)
归档时间: |
|
查看次数: |
2647 次 |
最近记录: |