Skip to content

控制流

🌐 Control flow

对于高级用法,选择提供了自定义控制流的方法。

🌐 For advanced usage, selections provide methods for custom control flow.

selection.each(function)

来源 · 对每个选中的元素按顺序调用指定的函数,传入当前数据(d)、当前索引(i)和当前组(nodes),其中this为当前 DOM 元素(nodes[i])。此方法可用于对每个选中的元素调用任意代码,并且在创建同时访问父数据和子数据的上下文时非常有用,例如:

js
parent.each(function(p, j) {
  d3.select(this)
    .selectAll(".child")
      .text(d => `child ${d.name} of ${p.name}`);
});

请参见 不同尺寸的甜甜圈倍数 作为示例。

🌐 See sized donut multiples for an example.

selection.call(function, ...arguments)

来源 · 精确调用指定的函数一次,将此选择以及任何可选的参数传入。返回此选择。这等同于手动调用函数,但便于方法链。例如,要在可重用函数中设置多个样式:

js
function name(selection, first, last) {
  selection
      .attr("first-name", first)
      .attr("last-name", last);
}

现在说:

🌐 Now say:

js
d3.selectAll("div").call(name, "John", "Snow");

这大致相当于:

🌐 This is roughly equivalent to:

js
name(d3.selectAll("div"), "John", "Snow");

唯一的区别是 selection.call 总是返回 selection,而不是被调用 function 的返回值 name

🌐 The only difference is that selection.call always returns the selection and not the return value of the called function, name.

selection.empty()

来源 · 如果此选择不包含任何(非空)元素,则返回 true。

js
d3.selectAll("p").empty() // false, here

selection.nodes()

来源 · 返回此选择中所有(非空)元素的数组。

js
d3.selectAll("p").nodes() // [p, p, p, …]

等同于:

🌐 Equivalent to:

js
Array.from(selection)

selection[Symbol.iterator]\(\)

🌐 selection[Symbol.iterator]()

来源 · 返回所选(非空)元素的迭代器。例如,要遍历所选元素:

js
for (const element of selection) {
  console.log(element);
}

要将选定对象展平为数组:

🌐 To flatten the selection to an array:

js
const elements = [...selection];

selection.node()

来源 · 返回此选择中的第一个(非空)元素。如果选择为空,则返回 null。

selection.size()

来源 · 返回此选择中(非空)元素的总数。