使用D3.js时Javascript闭包不能正确访问外部变量?

新手上路,请多包涵

在用d3.js v5版本,如下javascript代码片段

let colorData = [1, 2, 3, 4, 5, 6, 7, 8];
let colorSchemes = [
    d3.scaleOrdinal(d3.schemeCategory10),
    d3.scaleOrdinal(d3.schemeAccent),
    d3.scaleOrdinal(d3.schemePaired),
    d3.scaleOrdinal(d3.schemePastel1),
    d3.scaleOrdinal(d3.schemeDark2),
    d3.scaleOrdinal(d3.schemeSet1)
];

let scheme = colorSchemes[0];
let test_color = scheme(1); // test_color = #1f77b4

// here ignore some code about "svgs"
svgs.selectAll("circle")
    .data(colorData).enter()
    .append("circle")
    .attr("fill", (d, i) => {
        let scheme = colorSchemes[i];
        return scheme(d); // the console log "scheme is not a function"
    });

为什么test_color能正确取得值,而闭包内同样的代码不能正确执行?

阅读 2k
1 个回答
✓ 已被采纳新手上路,请多包涵

自问自答。
原来我把上面代码中的变量i的含义弄错了,i是colorData的索引号,不是colorSchemes的索引号。
下面的更正后的代码:

let colorData = [1, 2, 3, 4, 5, 6, 7, 8];
let colorSchemes = [
    d3.scaleOrdinal(d3.schemeCategory10),
    d3.scaleOrdinal(d3.schemeAccent),
    d3.scaleOrdinal(d3.schemePaired),
    d3.scaleOrdinal(d3.schemePastel1),
    d3.scaleOrdinal(d3.schemeDark2),
    d3.scaleOrdinal(d3.schemeSet1)
];

// here ignore some code about "svgs"
svgs.each(function (d, schemeIndex) {
    d3.select(this)
        .selectAll("circle")
        .data(colorData)
        .enter().append("circle")
        .attr("fill", (d, i) => {
            let scheme = colorSchemes[schemeIndex];
            return scheme(d);
        });
});
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题