Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
386 views
in Technique[技术] by (71.8m points)

d3.js - Third variable in D3 anonymous function

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").each(function(d,i,q) {console.log(d,i,q)})

We all know the first variable is the data and the second is the array position. But what does the third variable (q in this case) represent? So far it's always come back zero in everything I've tested.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...