我是 D3.js 的新手,我正在尝试用我的图表制作一些动画,
但我无法解决 .get()
的问题在 d3.map
上调用的方法适用于 D3 版本 6。
当我运行代码时,它会引发错误:
nodeById.get is not a function
我的代码基于:https://bl.ocks.org/ctufts/bd6956a45ea69734f5909c8b526c13b5
//some fetch data in json file
d3.json("someURLjsonfile").then(function (graph) {
let nodes = graph.nodes,
nodeById = d3.map(nodes, function (d) {
return d.id;
}),
links = graph.links,
bilinks = [];
links.forEach(function (link) {
var s = nodeById.get(link.source), // <-- error
t = nodeById.get(link.target), // <-- error
i = {}; // intermediate node
nodes.push(i);
links.push({
source: s,
target: i
}, {
source: i,
target: t
});
bilinks.push([s, i, t]);
});
最佳答案
您的问题是由一些相当不幸的 API 重新设计引起的。从 D3 v6 开始, d3-collection
模块已被弃用并从 D3 包中删除。该模块包含 d3.map()
将创建 d3.map
的构造方法对象,即模仿原生 JavaScript Map
的 D3 内部 map 实现之一.这种方法已经存在了一段时间,但是一旦 ES6 功能可用并因此被删除,它就失去了重要性。
遗憾的是,d3-array
的第 2 版module 引入了一个同名方法,基本相当于原生的array.map()
或 Array.from()
方法:
# d3.map(iterable, mapper) · Source
Returns a new array containing the mapped values from iterable, in order, as defined by given mapper function. Equivalent to array.map and Array.from:
由于
d3-array
v2 被引入到同版本 6 的捆绑包中,也删除了 d3-collection
d3.map
属性仍然可用,但是它的含义已经改变。您的代码似乎是为 D3
.get()
的数组方法,因此,错误。要解决此问题,您可以更改代码以直接使用内置
Map
改为对象:nodeById = new Map(Array.from(nodes, d => [d.id, d]));
其余部分保持不变,您的代码应该按预期运行。
关于javascript - map.get() 方法不适用于 D3 v6,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70202525/