确定给定的数组是d3选择

Identify given array is a d3 selection

本文关键字:d3 选择 数组      更新时间:2023-09-26

我如何识别给定的数组是d3选择。我已经试过了

function Chart(container, data) {
    var isd3Selection = container instanceof Array && typeof container.node === 'function';
    this.container = isd3Selection ? container.node() : container;
    this.data = data;
    this.init();
}

还有其他方法可以知道吗?

V4的做法:

根据文档

d3.selection ()

选择根元素document.documentElement。这个函数还可以用来测试选择(instanceof d3.selection)或扩展选择原型。例如,要添加一个选中复选框的方法:

你可以这样测试:

d3.select(document.body) instanceof d3.selection // true

根据你的D3版本,你可能会使用以下方法之一:

v3

正如我对"d3 "的回答所述。选择类型检查在IE 这需要一个小的解决方案。因为d3.selection是作为扩展选项功能的一种方式提供的,所以你可以在d3.selection中添加一个新的属性,这个属性可以被任何选项访问,无论是通过原型设计还是通过复制属性。

// Include this at the start of your script to include the
// property in any selection created afterwards.
d3.selection.prototype.isD3Selection = true;
d3.select(document.body).isD3Selection;   // true 
v4

从v4开始,一个选择不再只是一个嵌套数组,而是一个JavaScript对象,这将使生活更加简单。你可以使用标准的constructor属性来检查D3的选择:

d3.select(document.body).constructor.name === "Selection"   // true

请注意,这只会在使用O. R. Mapper在他们的评论中指出的D3的未缩小版本时起作用。对于v4,首选的解决方案应该使用instanceof操作符,如在老兄的回答中所述。