javascript - 谁能告诉我为什么地图大小为零?
问题描述
我正在学习 JS 中的数据结构并编写了一些代码来构建 Graph 数据结构。
但似乎有一个问题,我无法理解它为什么会发生。
请查看有关 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();
解决方案
if (!this.list[vertex]) {
this.list[vertex] = [];
这不是与地图内容交互的正确方式。这是合法的 javacript,但您将任意键/值对附加到地图对象,而不是实际将内容存储在地图中。
相反,请执行以下操作:
if (!this.list.has(vertex) {
this.list.set(vertex, []);
}
同样,当你想从地图中获取数据时,不要使用括号语法,使用this.list.get(vertex)
推荐阅读
- php - 如果由于 laravel rest api 中的外键错误而无法删除数据,则处理自定义消息
- php - 创建反转单词但保留任何空格的函数?
- typescript - 在打字稿的接口中使用枚举值作为类型
- javascript - 将函数添加到 DOM 元素中
- android - 如何将普通 Android 应用程序转换为 Android Auto 应用程序?
- javascript - 如何获取输入值,然后针对 0 索引处的所有数组对象值进行检查
- sql - 如何通过引用sql中的日期和状态进行排名
- r - 如何从 R 中的 multiples facet_grid 的子集中添加点?
- python-3.x - grouby 对象的形状及其转换后的数据框对象
- python - 如何在python中使用pynput输出每次按下空格键之间的时间