【问题标题】:Call a function with multiple parameters on a data object in D3在 D3 中的数据对象上调用具有多个参数的函数
【发布时间】:2015-10-01 08:56:06
【问题描述】:

我是 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;
}

【问题讨论】:

  • 看起来应该可以了。您能否提供一个重现问题的完整示例?

标签: javascript d3.js parameter-passing


【解决方案1】:

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

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

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

【讨论】:

  • 是的!你说得对,在我删除版本 1 后它可以工作,谢谢!
猜你喜欢
  • 2014-12-27
  • 1970-01-01
  • 2013-06-13
  • 2011-11-21
  • 1970-01-01
  • 2020-04-21
  • 2013-10-17
  • 2013-11-14
  • 1970-01-01
相关资源
最近更新 更多