我可以在D3选择中调用indexOf吗

Can I call indexOf within a D3 selection?

本文关键字:调用 indexOf 选择 D3 我可以      更新时间:2023-09-26

我正在使用D3制作条形图,D3使用数字数组dataset[]生成并设置条形图的高度。

我有一部分代码,它在鼠标悬停条形元素时生成工具提示。

d3.select("#tooltip")
    .style("left", xPosition + "px")
    .style("top", yPosition + "px")                     
    .select("#share-value")
    .text(d)
    .select("#month-now")
    .text(dataset.indexOf(d));
console.log(dataset.indexOf(d));

text(d)显示正确,这是dataset[d]的值。但是,我也想在dataset中显示元素d的索引。console.log(dataset.indexOf(d))会正确记录索引,但该索引不会显示在工具提示中。为什么会这样?

编辑:我也试过

.text(function (d, i) {
        return i;
    });

根据D3 Selections,但它似乎仍然没有返回当前数据的索引。

我假设您的数据集是一个对象数组。所以你应该使用这样的东西:

//imagine your dataset like this:
var dataset = [{name:"cyril", age: 34}, {name:"Tow", age: 3}]

因此,当你试图获得索引时,你必须这样做:

dataset.findIndex(function(d){ return "cyril" == d.name})
//this will return 0 and for Tow return 1 and "Bow" will return -1

因此,在您的代码中,它将是这样的:

d3.select("#tooltip")
    .style("left", xPosition + "px")
    .style("top", yPosition + "px")                     
    .select("#share-value")
    .text(d)
    .select("#month-now")
    .text(function(d1){dataset.findIndex(function(d){ return YOUR_CONDITION})});

希望这能有所帮助!

mouseover监听器的第二个参数将为您提供d的索引。

.on("mouseover",function(d,i){ //i is the index of d in the dataset
   d3.select("#tooltip")
    .style("left", xPosition + "px")
    .style("top", yPosition + "px")                     
    .select("#share-value")
    .text(d)
    .select("#month-now")
    .text(i);
});