Every D3js beginner must be going through this thought, I am pretty much sure about it.
I have been around this thing for few hours now!!!!But I don\'t
Your example is a good illustrator of the difference between the two.
In the first example, only d
is used. d
represents the data associated with a given selection. In this case, an array of selected div
elements is created, one for each element in the data
array:
chart.selectAll("div")
.data(data)
.enter()
.append("div")
This not only creates an array of div
elements, but associates data with each of those elements. This is done on a one-to-one basis, with each div
corresponding to a single element in the data
array. One is associated with '4', one with '8', and so on.
If I then go on to use .text(function(d){...})
on the array of selections, d
will refer to the data associated with each selected div, so if I use the following method on my selections:
.text(function(d) { return d; });
Each of my div
s will have text added, the value of which is d
, or the data associated with the element.
When an array of selections is created, they are also given an index in the array. In your example, this corresponds to the position of their data in the data array. If your function requests both d
and i
, then i
will correspond to this index. Going back to our div
s, the div
associated with '4' will have an index of '0', '8' will have an index of '1', and so on.
It's also important to note that the character used in the variable requested doesn't matter. The first variable in the function call is always the data, and the second is the index. If i used a method like
.text(function(cat,moose){ return( "data is: " + cat + " index is: " + moose)})
cat
will correspond to the data of the selection, and moose
will correspond to the index.