使用" d"在D3中的函数文字?

时间:2014-06-23 05:22:18

标签: function d3.js literals

我在教自己D3没有太多关于javascript语法/语法的知识。 任何人都可以解释使用" d"作为以下函数文字中的参数?

我看到它指向正在处理的数据集,但想要理解这背后的语法。

    d3.selectAll("circle")
        .attr("cy",function (d) { return percent_scale(d.late_percent);})
        .attr("cx",function (d) { return time_scale(d.time);})
        .attr("r",1);

1 个答案:

答案 0 :(得分:36)

这称为匿名函数,它是一个未赋予命名标签的函数。 Javascript中的匿名函数就像其他所有对象一样,这就是为什么你可以将它们作为参数传递给其他javascript函数。

在d3的情况下,它允许您传入一个函数作为第二个参数。正如您所发现的,将使用当前数据元素以及当前数据元素的索引来调用此函数。如果第二个参数不是函数,则可以使用值。

在你的例子中:

d3.selectAll("circle")
        .attr("cy",function (d) { return percent_scale(d.late_percent);})
        .attr("cx",function (d) { return time_scale(d.time);})
        .attr("r",1);

基于匿名函数调用的返回值为cycx分配值,而为r分配静态值。我们可以将其重写为:

function setY(d) { return percent_scale(d.late_percent);}

function setX(d) { return time_scale(d.time); }

d3.selectAll("circle")
        .attr("cy", setY)
        .attr("cx", setX)
        .attr("r",1);

这里我用更多标准函数定义替换了匿名函数调用,并在d3调用中指定了要调用的函数的名称。这与以前完全相同。另请注意,在这种情况下,d没有什么神奇之处。

function setY(foo) { return percent_scale(foo.late_percent);}

function setX(foo) { return time_scale(foo.time); }

d3.selectAll("circle")
        .attr("cy", setY)
        .attr("cx", setX)
        .attr("r",1);

此代码也会做同样的事情。请注意,我已将参数从d重命名为foo,但这只会更改您在函数中访问参数的方式。它在函数调用之外没有任何影响。通常在d3文档和教程中,您会看到d用于当前数据元素,i用于当前数据元素的索引。索引作为第二个元素传入函数调用,如下所示:

function setY(d, i) { return percent_scale(d.late_percent);}

function setX(d, i) { return time_scale(d.time); }

d3.selectAll("circle")
        .attr("cy", setY)
        .attr("cx", setX)
        .attr("r",1);

现在特别在d3案例中:

// Select all of the 'circle' elements (that is <circle>) elements
// in the HTML document and put the associated data into an array
d3.selectAll("circle")

        // For each circle element, set the Y position to be the result
        // of calling percent_scale on the data element late_percent
        .attr("cy",function (d) { return percent_scale(d.late_percent);})

        // For each circle element, set the X position to be the result
        // of calling time_scale on the data element time
        .attr("cx",function (d) { return time_scale(d.time);})

        // For each circle element, set the radius to be 1
        .attr("r",1);

这是d3中非常常见的构造。第一步始终是选择以定义要修改的元素集(在这种情况下,这是.selectAll)。之后,您可以将实际执行所需修改的其他调用(在本例中为.attr调用)链接在一起。

这创建了一种非常强大的方法来处理数据驱动的文档(如图形,图表等),而无需手动跟踪数据元素或必须创建大量循环。实际上,如果代码中有任何涉及修改元素的循环,通常可以告诉您错误地使用d3

如果您对javascript没有太多经验,https://www.dashingd3js.com/上的教程可能对d3入门有帮助。