d3.js - .each() 带过滤器

标签 d3.js typeerror

我正在查看另一个 stackoverflow 问题,并尝试了以下操作:

d3.selectAll(links.filter(function(db) {
  return db.source.id == 'foo'
})).each(function(p) {
      console.log (p.source.id)
    })

并且发现它返回了一个

TypeError: Cannot read property 'source' of undefined

即使筛选后的选择返回为具有 .source.id 值的正确对象数组(此示例使用 D3 的力导向网络中的标准链接符号)。

我很好奇为什么这行不通。

最佳答案

确保您清楚自己使用的是以下两种方法中的哪一种:

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/filter https://github.com/mbostock/d3/wiki/Selections#wiki-filter

d3.selectAll 函数接受一个选择器字符串或一个 DOM 节点数组。你的情况是哪一种?

https://github.com/mbostock/d3/wiki/Selections#wiki-d3_selectAll

请记住,selection.each() 回调函数中的变量 p 对应于绑定(bind)到选择中的元素的数据。

https://github.com/mbostock/d3/wiki/Selections#wiki-each


更新

您的 links 变量似乎是一个常规 JavaScript 对象数组。这是不正确的,因为 d3.selectAll 函数需要 DOM 节点数组(或选择器字符串)。有趣的是,如果您使用常规数组作为参数,它不会报错;例如,您仍然可以调用 selection.each 方法:

selection.each(function)

Invokes the specified function for each element in the current selection, passing in the current datum d and index i, with the this context of the current DOM element. This operator is used internally by nearly every other operator, and can be used to invoke arbitrary code for each selected element. The each operator can be used to process selections recursively, by using d3.select(this) within the callback function.

但是,因为选择不是真正选择绑定(bind)了数据的 DOM 节点,所以您会看到函数中的第一个参数(通常是 d,在您的例子中是 p)将是未定义的。

第二个参数,索引 i,仍然对应于我们正在迭代的原始数组的索引。这就是为什么 d3.selectAll(links).each(function(p, i) { console.log(links[i].source.id); }) 为您工作的原因。它基本上与这个(非 d3)JavaScript 表达式做同样的事情:links.forEach(function(v, i) { console.log(links[i].source.id); })

您正在查看的内容的另一个简化示例:

// anti-pattern:
var arr = ['a', 'b', 'c'];
d3.selectAll(arr)
    .each(function(d, i) {
      console.log(d, i, arr[i]);
    });

哪个日志到控制台:

undefined 0 "a"
undefined 1 "b"
undefined 2 "c"

因此,相反,如果您尝试检查力导向布局中的链接,您可以选择代表这些链接的 DOM 节点。以 D3 库中包含的标准力为例:http://d3-example.herokuapp.com/examples/force/force.htm并从控制台运行以下命令:

d3.selectAll('line')
    .each(function(d, i) {
      console.log(d.source.index);
    });

关于d3.js - .each() 带过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14218016/

相关文章:

javascript - 根据算术级数动态分配高度

javascript - 如何调用嵌套 JSON 数据中的所有值 (d3js)

javascript - 这个错误是什么意思——Uncaught TypeError : Already read?

python - socket.py : TypeError: a float is required 上的深度错误

Python 3 : TypeError: can't multiply sequence by non-int of type 'float'

javascript - 如何自定义X轴的标签,即X轴的标签与数据不同

d3.js - 在 d3 中旋转和翻译文本的正确方法是什么?

javascript - D3 V4 设置初始缩放级别

Javascript:TypeError:...不是构造函数

javascript - 类型错误:a.dot(...).equals 不是函数