D3中的第三个变量匿名函数 [英] Third variable in D3 anonymous function

查看:135
本文介绍了D3中的第三个变量匿名函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您选择了一些与其绑定的数据,并使用典型的内联匿名函数访问该数据:

  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 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.

这篇关于D3中的第三个变量匿名函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆