如何在对象中使用字符串变量?

时间:2013-06-13 13:35:36

标签: javascript

我有一个字符串,如果我在控制台中记录它,它看起来像这样:

0.0196078431373,0.078431372549,0.0196078431373,0.0392156862745,0.0196078431373,0.0196078431373,0.0196078431373,0.0588235294118,0.0588235294118

我尝试在图表的对象中使用它,如下所示:

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]
                        }
                    ]   
                }

但strTags没有打印(数字),它显示如上。我怎么能解决这个问题,它显示如下:

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]
                        }
                    ]   
                }

3 个答案:

答案 0 :(得分:1)

您需要首先将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(',')
        }
     ]   
}

答案 1 :(得分:0)

如果您需要它是一个数字数组,那么您必须将字符串解析为浮点数。你可以这样做:

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);
            })
        }
     ]   
}

答案 2 :(得分:0)

另一个解决方案是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 + "]");
        }
     ]   
}