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

D3.js key function running twice on simple selector/array combo

本文关键字:运行 组合 两次 数组 功能 js 简单 选择器 D3      更新时间:2023-09-26

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

这是 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(的原因是,当数据是对象数组并且我尝试引用函数中的键时,它会抛出一个未定义的错误。

从 d3 帮助:

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

您在第一个循环中看到的是遍历现有数据(没有(,然后是新数据数组(具有您期望的值(。如果你的键功能依赖于一个对象,你需要先做一个检查,以确保对象存在。