Third variable in D3 anonymous function

后端 未结 2 1409
名媛妹妹
名媛妹妹 2020-12-10 13:38

Let\'s say you\'ve got a selection with some data bound to it and you use the typical inline anonymous function to access that data:

 d3.select(\"#whatever\"         


        
2条回答
  •  春和景丽
    2020-12-10 14:24

    The secret third argument is only of use when you have nested selections. In these cases, it holds the index of the parent data element. Consider for example this code.

    var sel = d3.selectAll("foo").data(data).enter().append("foo");
    var subsel = sel.selectAll("bar").data(function(d) { return d; }).enter().append("bar");
    

    Assuming that data is a nested structure, you can now do this.

    subsel.attr("foobar", function(d, i) { console.log(d, i); });
    

    This, unsurprisingly, will log the data item inside the nesting and its index. But you can also do this.

    subsel.attr("foobar", function(d, i, j) { console.log(d, i, j); });
    

    Here d and i still refer to the same things, but j refers to the index of the parent data element, i.e. the index of the foo element.

提交回复
热议问题