鍍金池/ 問答/HTML/ 使用D3.js時Javascript閉包不能正確訪問外部變量?

使用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能正確取得值,而閉包內同樣的代碼不能正確執(zhí)行?

回答
編輯回答
陪她鬧

自問自答。
原來我把上面代碼中的變量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);
        });
});
2017年8月27日 05:47