gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 12:07:24 24 4
gpt4 key购买 nike

我正在使用 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})});

希望这对您有所帮助!

关于javascript - 我可以在 D3 选择中调用 indexOf 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34783926/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com