[英]How do I use a string variable in an object?
I have a string, that looks like this if I log it in the console: 我有一个字符串,如果我在控制台中将其记录为:
0.0196078431373,0.078431372549,0.0196078431373,0.0392156862745,0.0196078431373,0.0196078431373,0.0196078431373,0.0588235294118,0.0588235294118
I try to use it in an object for a chart, like this: 我尝试在图表对象中使用它,如下所示:
var barChartData = {
labels : ["People (2.5%)","War (2.1%)","Sharing (0.8%)","Animals (1.4%)","Friends (0.3%)"],
datasets : [
{
fillColor : "rgba(74,219,168,0.8)",
strokeColor : "rgba(56,193,145,1)",
data : [strTags]
}
]
}
But the strTags isn't printed (the numbers), it shows like above. 但是没有显示strTags(数字),如上所示。 How can I fix this that it shows like this:
我该如何解决显示如下的问题:
var barChartData = {
labels : ["People (2.5%)","War (2.1%)","Sharing (0.8%)","Animals (1.4%)","Friends (0.3%)"],
datasets : [
{
fillColor : "rgba(74,219,168,0.8)",
strokeColor : "rgba(56,193,145,1)",
data : [0.0196078431373,0.078431372549,0.0196078431373,0.0392156862745,0.0196078431373,0.0196078431373,0.0196078431373,0.0588235294118,0.0588235294118]
}
]
}
You need to convert the String to an array first, eg, by using split()
: 您需要首先将String转换为数组,例如,使用
split()
:
var barChartData = {
labels : ["People (2.5%)","War (2.1%)","Sharing (0.8%)","Animals (1.4%)","Friends (0.3%)"],
datasets : [
{
fillColor : "rgba(74,219,168,0.8)",
strokeColor : "rgba(56,193,145,1)",
data : strTags.split(',')
}
]
}
If you need it to be an array of numbers then you have to parse the string to a floating point number. 如果需要将其作为数字数组,则必须将字符串解析为浮点数。 You can do this:
你可以这样做:
var barChartData = {
labels : ["People (2.5%)","War (2.1%)","Sharing (0.8%)","Animals (1.4%)","Friends (0.3%)"],
datasets : [
{
fillColor : "rgba(74,219,168,0.8)",
strokeColor : "rgba(56,193,145,1)",
data : strTags.split(',').map(function(element, index, array) {
return parseFloat(element);
})
}
]
}
Another solution is JSON.parse 另一个解决方案是JSON.parse
var barChartData = {
labels : ["People (2.5%)","War (2.1%)","Sharing (0.8%)","Animals (1.4%)","Friends (0.3%)"],
datasets : [
{
fillColor : "rgba(74,219,168,0.8)",
strokeColor : "rgba(56,193,145,1)",
data : JSON.parse("["+ strTags + "]");
}
]
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.