首页 > 解决方案 > 谁能告诉我为什么地图大小为零?

问题描述

我正在学习 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();

标签: javascriptecmascript-6

解决方案


if (!this.list[vertex]) {
  this.list[vertex] = [];

这不是与地图内容交互的正确方式。这是合法的 javacript,但您将任意键/值对附加到地图对象,而不是实际将内容存储在地图中。

相反,请执行以下操作:

if (!this.list.has(vertex) {
  this.list.set(vertex, []);
}

同样,当你想从地图中获取数据时,不要使用括号语法,使用this.list.get(vertex)


推荐阅读