为什么转换时d3匿名函数中的第三个变量未定义?

时间:2016-06-12 05:10:42

标签: d3.js

假设我们有一些测试数据

var testdata1 = [
[
  {x: 1, y: 40},
  {x: 2, y: 43},
  {x: 3, y: 12},
  {x: 4, y: 60},
  {x: 5, y: 63},
  {x: 6, y: 23}
], [
  {x: 1, y: 12},
  {x: 2, y: 5},
  {x: 3, y: 23},
  {x: 4, y: 18},
  {x: 5, y: 73},
  {x: 6, y: 27}
], [
  {x: 1, y: 60},
  {x: 2, y: 49},
  {x: 3, y: 16},
  {x: 4, y: 20},
  {x: 5, y: 92},
  {x: 6, y: 20}
 ] 
];

我们将数据绑定到一些嵌套对象,比如

var circles = svg.select("circle")
    .data(testdata1)
    .enter()
    .append("circle")
var subsel = circles.selectAll("rect")
    .data(function(d) {return d})
    .enter()
    .append("rect")

d3匿名函数中的第三个变量保存父数据元素的索引(如Third variable in D3 anonymous function中所述)。

在添加转换之前,j变量的行为与预期相同(每组6个元素的值为0,1,2)。

然而,在转换之后,j变量变为未定义:

subsel.attr("foobar", function(d,i,j) {console.log(d,i,j)})
    .transition()
    .attr("foobar", function(d,i,j) {console.log(d,i,j)})   

发生了什么事?

1 个答案:

答案 0 :(得分:1)

转换后第三个变量不会变为未定义。您可以轻松地在这个小提琴中查看它:https://jsfiddle.net/gerardofurtado/4jahe31t/2/

我将console.log更改为“之前”和“之后”:

subsel.attr("foobar", function(d,i,j) {console.log("before: 
    x=" + d.x + " y=" + d.y + " i=" + i + " j=" + j)})
.transition()
.attr("foobar", function(d,i,j) {console.log("after: 
    x=" + d.x + " y=" + d.y + " i=" + i + " j=" + j)})

按预期显示父索引:

after: x=1 y=40 i=0 j=0
after: x=2 y=43 i=1 j=0
after: x=3 y=12 i=2 j=0
after: x=4 y=60 i=3 j=0
after: x=5 y=63 i=4 j=0
after: x=6 y=23 i=5 j=0
after: x=1 y=12 i=0 j=1
etc...

我尝试重现行为,逐字复制代码,但我仍然获得j的值。

相关问题