问题描述
因此,我正在尝试通过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),那么我得到this log in console 我在此处粘贴的图形编号带有一个包名称为chartist-plugin-tooltips的包,所以也许我必须在此处进行一些更改,我不知道。
解决方法
它正在尝试针对字符串而不是数组运行.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,"."))