在 D3 中的数据对象上调用具有多个参数的函数

Call a function with multiple parameters on a data object in D3

我是 D3 和 JS 的新手,正在尝试了解如何在 D3 中的数据对象上调用具有多个参数的函数。在我的尝试之下。问题是我如何使版本 2 工作?

d3.csv(input_file, function(data) {

    var metric = "foo";

    // Version 1:
    // clean number format. works fine
    data.forEach(function(d) {
        d[metric] = +d[metric].replace(/,/g,''); //remove thousand separator
        return d;
    });

    //Version 2:
    // this doesn't work. why not?
    // [Error] TypeError: undefined is not a function (evaluating 'd[metric].replace(/,/g,'')')
        data.forEach(function(d) {
          return cleanNumberFormat(d, metric);
        });

    // ...
});

// define a function to be used in several places
function cleanNumberFormat(d, metric) {
    d[metric] = +d[metric].replace(/,/g,''); //remove thousand separator
    return d;
}

如果您删除版本 1 并保留版本 2,则该代码有效。根本原因是版本 1 中的这一行:

d[metric] = +d[metric].replace(/,/g,''); //remove thousand separator

注意加号 +。它将替换结果从类型 String 转换为 Number。显然 Number 没有 replace 功能,所以你得到了版本 2 的错误。