D3.js关键函数在简单的选择器/数组组合上运行两次

时间:2014-12-20 05:41:11

标签: javascript d3.js

学习d3,当我创建一个简单的数字数组时,然后尝试将数据绑定到一组简单的元素,但是使用键函数,它会在循环中运行两次。第一次,它告诉我数组的值是未定义的。第二次通过他们是可用的。

这是html:

<div class="testBind"></div>
<div class="testBind"></div>
<div class="testBind"></div>

这是js:

var numbers = [1, 2, 3];

function whichNumber(n){
    console.log('n----:' + n);
    return n;
}

var testKeyFunction = d3.selectAll("div.testBind").data(numbers, whichNumber);

当我跑步时,我得到:

n----:undefined
n----:undefined
n----:undefined
n----:1
n----:2
n----:3

这是一个小提琴手:http://jsfiddle.net/5f8mo2sa/3/

这是一个问题(除了wtf)的原因是因为当数据是一个对象数组并且我尝试引用函数中的一个键时,它会抛出一个未定义的错误。

1 个答案:

答案 0 :(得分:4)

来自d3帮助:

可以指定一个键功能来控制数据如何连接到元素。这将替换默认的by-index行为;关键function is invoked once for each element in the new data array, and once again for each existing element in the selection。在这两种情况下,键函数都传递给数据d和索引i。当在新数据元素上评估关键函数时,该上下文是数据数组;当在现有选择上评估关键函数时,此上下文是关联的DOM元素。

您在第一个循环中看到的是通过现有数据(没有),然后它通过新数据数组(具有您期望的值)。如果键功能取决于对象,则需要先进行检查以确保对象存在。