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

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

问题描述

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

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)})

我们都知道第一个变量是数据,第二个是数组位置.但是第三个变量(在本例中为 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");

假设 data 是一个嵌套结构,您现在可以这样做.

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); });

这里di仍然指的是同一个东西,但是j指的是父数据元素的索引,即foo元素的索引.

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天全站免登陆