Skip to content

控制流

¥Control flow

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

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

selection.each(function) {#selection_each}

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

¥Source · Invokes the specified function for each selected element, in order, being passed the current datum (d), the current index (i), and the current group (nodes), with this as the current DOM element (nodes[i]). This method can be used to invoke arbitrary code for each selected element, and is useful for creating a context to access parent and child data simultaneously, such as:

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) {#selection_call}

源代码 · 仅调用一次指定函数,并将当前选择项及其所有可选参数传入。返回此选择。这相当于手动调用该函数,但有助于方法链式调用。例如,在可重用函数中设置多个样式:

¥Source · Invokes the specified function exactly once, passing in this selection along with any optional arguments. Returns this selection. This is equivalent to invoking the function by hand but facilitates method chaining. For example, to set several styles in a reusable function:

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 始终返回选择,而不是被调用函数 name 的返回值。

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

selection.empty() {#selection_empty}

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

¥Source · Returns true if this selection contains no (non-null) elements.

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

selection.nodes() {#selection_nodes}

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

¥Source · Returns an array of all (non-null) elements in this selection.

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

等同于:

¥Equivalent to:

js
Array.from(selection)

selectionSymbol.iterator {#selection_iterator}

源代码 · 返回一个遍历选定(非空)元素的迭代器。例如,迭代选定元素:

¥Source · Returns an iterator over the selected (non-null) elements. For example, to iterate over the selected elements:

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

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

¥To flatten the selection to an array:

js
const elements = [...selection];

selection.node() {#selection_node}

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

¥Source · Returns the first (non-null) element in this selection. If the selection is empty, returns null.

selection.size() {#selection_size}

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

¥Source · Returns the total number of (non-null) elements in this selection.