我和D3 v4做了一个项目。但是,我在理解使用selection.data()使用关键函数绑定数据时遇到了问题。
var data = [
{"id": 1},
{"id": 1}
];
var nodes = d3.selectAll("g").data(data, function(d){
return d.id;
})
console.log(nodes.enter());为什么nodes.enter().nodes().length等于2?然后,我尝试使用相同的id推送数据;在nodes.enter() https://jsfiddle.net/Fboy/2jo3Lm6z/中也是如此,为什么会发生这种情况?
发布于 2016-10-22 09:17:40
键函数本身并不能保证数据的唯一性。如果您想要您的数据是明确可识别的,您需要提供一个合适的关键功能。数据绑定对重复密钥的行为在selection.data()中有很好的文档记录。
如果多个数据具有相同的键,则将重复的数据放入enter选择中。
在应用来源策略时,bindKey中也记录了相同的内容:
// Compute the key for each datum.
// If there a node associated with this key, join and add it to update.
// If there is not (or the key is a duplicate), add it to enter.
for (i = 0; i < dataLength; ++i) {
keyValue = keyPrefix + key.call(parent, data[i], i, data);
if (node = nodeByKeyValue[keyValue]) { // [ac]: check if node exists for this key
update[i] = node;
node.__data__ = data[i];
nodeByKeyValue[keyValue] = null; // [ac]: will put duplicate data to enter
} else { // [ac]: no corresponding node found
enter[i] = new EnterNode(parent, data[i]);
}
}表示[ac]的评论是我的。
因此,如果绑定包含两个具有相同键的对象的数组,并且不存在匹配该键的节点,则这两个数据都将被放入enter选择中。
发布于 2016-10-22 06:51:07
实际上,因为在D3 v4.x中,选择不再是数组,而是对象,这是:
console.log(nodes.enter().length)将返回undefined。但这一点:
console.log(nodes.enter().nodes())将返回:
[EnterNode, EnterNode]它是一个包含"enter“选择的两个元素的数组。因此:
console.log(nodes.enter().nodes().length)将返回2。
https://stackoverflow.com/questions/40189010
复制相似问题