首页 > 解决方案 > 向 chartist.js 添加千位分隔符

问题描述

所以我试图在图表编号中添加千位分隔符,使用 npm 包图表师制作。我尝试实现的方式是下一个:


    const data = {
          // A labels array that can contain any sort of values
          labels: this.props.labels.toString().replace(/\B(?=(\d{3})+(?!\d))/g, "."),
          // Our series array that contains series objects or in this case series data arrays
          series: [this.props.data]
        };

我试图改变包本身,但每次我得到下一个错误:


    Uncaught TypeError: Cannot assign to read only property 'length' of object '[object String]'
        at String.push (<anonymous>)
        at Object.Chartist.normalizeData (chartist.js:400)
        at constr.createChart (chartist.js:3387)
        at constr.initialize (chartist.js:1940)

我也尝试将其实现为一个函数:


    function(label){label.value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");}

但随后它表明 data.labels(来自 npm 包)不是一个函数。

编辑1: 如果我console.log(this.props.labels)然后我在控制台中得到这个日志 我用包名chartist-plugin-tooltips粘贴在那里的图表编号,所以也许我必须在那里改变一些东西,我没有'不知道。

标签: reactjschartist.js

解决方案


它试图.push针对字符串而不是数组运行。我假设标签应该是一个数组,但.replace会返回一个字符串。

也许您打算使用.split()将标签转换回数组。从 toString() 你将有一个字符串,它是一个逗号分隔的数组值列表。因此,您将不得不使用逗号再次对其进行拆分。例如

labels: this.props.labels.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".").split(',')

编辑

如果您的数组值有逗号,您将需要使用不同的分隔符.join,而不是.toString.

    this.props.labels.join('$').replace(/\B(?=(\d{3})+(?!\d))/g, ".").split('$')

最终编辑

如果您实际上并未向数组添加值,那么通过元素进行映射会更干净!当我再次阅读您的问题时,我意识到这一点有点晚。

this.props.labels.map(label => label.toString().replace(/\B(?=(\d{3})+(?!\d))/g, "."))

推荐阅读