Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/408.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何使用带有ES6箭头符号的d3的每个方法_Javascript_D3.js - Fatal编程技术网

Javascript 如何使用带有ES6箭头符号的d3的每个方法

Javascript 如何使用带有ES6箭头符号的d3的每个方法,javascript,d3.js,Javascript,D3.js,出于某种原因,d3在每次迭代中使用它来引用a.中的当前元素 我有这个密码: var me = this; ... d3.selectAll(".region").each(function(d) { d3.select(this).style("fill", me.compute_color(...)); }) 对于ES6,我可以使用箭头符号来避免覆盖它: 但是,此代码不起作用,因为d3选择了错误的元素。事实上,我丢失了对元素的唯一引用,因为d3没有覆盖它 如何更改d3。选择此选项使其

出于某种原因,d3在每次迭代中使用它来引用a.中的当前元素

我有这个密码:

var me = this;
...
d3.selectAll(".region").each(function(d) {
    d3.select(this).style("fill", me.compute_color(...));
})
对于ES6,我可以使用箭头符号来避免覆盖它:

但是,此代码不起作用,因为d3选择了错误的元素。事实上,我丢失了对元素的唯一引用,因为d3没有覆盖它


如何更改d3。选择此选项使其工作?

您可以使用作为第二个参数传递的索引从集合中访问正确的元素:

let selection = d3.selectAll(".region");
selection.each((d, i) => {
    d3.select(selection[0][i]).style("fill", this.compute_color(...));
})

不是100%确定,但我认为如果不更改d3.1,您就不能更改每个代码,因为arrow函数不会选择由其代码发送到节点的this。因此,对于那些情况,保持传统的方式是最好的问题是,我从任何地方都删除了旧的我。。。我不想回滚所有内容嗯,也许你可以自己迭代:d3.selectAll.region[0]。forEachd=>{d3.selectd.stylefill,this.compute_color…;}但是这里d将引用d3元素而不是数据,或者使用它们的每个代码作为引用来创建你自己的eachArrow函数:你不能在胖箭头上使用自定义的this,在创建时生效的一个是烘焙的,就像闭包一样。。。
let selection = d3.selectAll(".region");
selection.each((d, i) => {
    d3.select(selection[0][i]).style("fill", this.compute_color(...));
})