D3中的第三个变量匿名函数 [英] Third variable in D3 anonymous function
问题描述
假设您选择了一些与其绑定的数据,并使用典型的内联匿名函数访问该数据:
d3.select(#whatever)。each(function(d,i,q){console.log(d,i,q)})
pre>
我们都知道第一个变量是数据,第二个是数组位置。但是第三个变量(在这种情况下是q)代表什么?
解决方案秘密的第三个参数只有在你已经测试的时候才会使用。 嵌套选择。在这些情况下,它保存父数据元素的索引。考虑这个代码。
var sel = d3.selectAll(foo)。data(data).enter .append(foo);
var subsel = sel.selectAll(bar)。data(function(d){return d;})enter()。append(bar);
假设
data
是一个嵌套结构,您现在可以这样做。subsel.attr(foobar,function(d,i){console.log , 一世); });
这并不奇怪,会将数据项记录在嵌套及其索引中。但你也可以这样做。
subsel.attr(foobar,function(d,i,j){console。 log(d,i,j);});
这里
d
和i
仍指向相同的东西,但j
是指父数据元素的索引,即foo
元素的索引。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.
解决方案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
andi
still refer to the same things, butj
refers to the index of the parent data element, i.e. the index of thefoo
element.这篇关于D3中的第三个变量匿名函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!