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

use*_*812 12 function literals d3.js

我在教自己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);
Run Code Online (Sandbox Code Playgroud)

Bil*_*ill 38

这称为匿名函数,它是一个未给出命名标签的函数.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);
Run Code Online (Sandbox Code Playgroud)

根据匿名函数调用的返回值为两者cy和/或者cx分配值,同时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);
Run Code Online (Sandbox Code Playgroud)

在这里,我用更标准的函数定义替换了匿名函数调用,并指定了调用中要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);
Run Code Online (Sandbox Code Playgroud)

这段代码也会做同样的事情.请注意,我已将参数重命名dfoo,但这只会更改您在函数中访问参数的方式.它在函数调用之外没有任何影响.通常在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);
Run Code Online (Sandbox Code Playgroud)

现在特别是在这种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);
Run Code Online (Sandbox Code Playgroud)

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

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

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