简体   繁体   English

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

[英]Call a function with multiple parameters on a data object in D3

I'm new to D3 and JS and try to understand how to call a function with multiple parameters on a data object in D3. 我是D3和JS的新手,并试图了解如何在D3中的数据对象上调用具有多个参数的函数。 Below my attempt. 低于我的尝试。 The question is how would I make version 2 work? 问题是如何使版本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;
}

The code works if you remove version 1 and leave version 2 alone. 如果删除版本1并保留版本2,则该代码有效。 The root cause is this line in version 1: 根本原因是版本1中的这一行:

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

Note the plus sign + . 注意加号+ It converts the replace result from type String to Number . 它将替换结果从String类型转换为Number Obviously Number does not have replace function, so you got the error in version 2. 显然, Number没有replace功能,因此在版本2中出现了错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM