ES6 中的 Map() 错误
2018-06-09
285
我尝试在 React、Redux 中实现 DFS 算法以将其可视化。
要创建邻接表,我使用 JavaScript 中的
Map()
数据结构:
dfs(v, visited, adjList) {
console.log(v);
visited[v] = true;
var get_neighbours = adjList.get(v);
for (var i in get_neighbours) {
var get_elem = get_neighbours[i];
if (!visited[get_elem])
this.dfs(get_elem, visited, adjList);
}
}
dfsStart(e) {
var n = 0;
var adjList = new Map();
for (var i = 0; i < this.props.edges.length; i++) {
n = Math.max(this.props.edges[i].u, this.props.edges[i].v);
}
for (var i = 1; i <= n; i++) {
adjList.set(i, []);
}
for (var key of adjList.keys()) {
console.log(key);
}
//console.log(adjList.size);
for (var i = 0; i < this.props.edges.length; i++) {
var x = this.props.edges[i].u;
var y = this.props.edges[i].v;
console.log(x + " " + y);
[...adjList.get(x), y] - > where I am getting error
}
for (var key of adjList.values()) {
console.log(key);
}
var visited = [];
for (i = 1; i <= n; i++) {
visited[i] = false;
}
this.dfs(1, visited, adjList);
}
我甚至尝试使用
push()
方法将值推送到空列表中,如下所示
adjList.get(x).push(y)
但这也给了我一个错误!
Uncaught TypeError: Cannot convert undefined or null to object at Function.from ()
当我使用
push()
时:
Layout.js:72 Uncaught TypeError: Cannot read property
push
of undefined at Layout.dfsStart (Layout.js:72)
2个回答
我猜你想将最大的 x 值放入
n
中,而不是最后一个 x 或 y,请更改:
for(var i=0;i<this.props.edges.length;i++)
n = Math.max(this.props.edges[i].u, this.props.edges[i].v);
更改为:
n = Math.max(...this.props.edges.map(edge => edge.u));
Jonas Wilms
2018-06-09
dfs(v, visited, adjList) {
console.log(v);
visited[v] = true;
var get_neighbours = adjList.get(v);
console.log(get_neighbours);
for (var i in get_neighbours) {
var get_elem = get_neighbours[i];
//console.log(get_elem);
if (!visited[get_elem]) {
this.dfs(get_elem, visited, adjList);
}
}
}
dfsStart(e) {
var n = 0;
var adjList = new Map();
for(var i=0;i<this.props.edges.length;i++) {
n = Math.max(n, Math.max(this.props.edges[i].u, this.props.edges[i].v));
adjList.set(this.props.edges[i].u, []);
}
for(var i=0;i<this.props.edges.length;i++) {
adjList.get(this.props.edges[i].u).push(this.props.edges[i].v);
}
var visited = [];
for(i=1;i<=n;i++) {
visited[i] = false;
}
this.dfs(1, visited, adjList);
}
这样做可以解决问题,但是当我使用 console.log(get_neighbours) 时,dfs() 函数仍然会出现未定义的错误,
Gagan Ganapathy
2018-06-09