0

我有一个字符串变量,我定义为:

var regn="[1,75],[2,59],[3,66],[4,92],[5,67],[6,77],[7,75],[8,80],[9,67],[10,56],[11,67],";

我还使用了一些 javascript 代码,它获取数组中的值并从这些值中绘制折线图。部分代码如下所示。

    var graphData = [{
        data: [[1,75],[2,59],[3,66],[4,92],[5,67],[6,77],[7,75],[8,80],[9,67],[10,56],[11,67],],
        color: '#77b7c5',
        points: { radius: 4, fillColor: '#77b7c5' }
    }
];

我试图用我上面定义的变量替换数组中的数据,但是当我这样做时图表不起作用。这是我的代码:

var graphData = [{
        data: [regn],
        color: '#77b7c5',
        points: { radius: 4, fillColor: '#77b7c5' }
    }
];

我哪里出错了,或者我应该如何将我的字符串中的数据获取到该数组?

4

4 回答 4

4

You need to parse the string first. This is usually done using JSON.parse:

var regn="[[1,75],[2,59],[3,66],[4,92],[5,67],[6,77],[7,75],[8,80],[9,67],[10,56],[11,67]]";
var arr = JSON.parse(regn) // now it's an Array

If you need to support browsers that don't support JSON.parse you can patch this using JSON3

Aside: In addition to that please notice that regn has a stray trailing comma and needs to be wrapped in a [] or {} (the object approach would also need keys then, so the array is the way to go here), so it's not valid JSON the way you have posted it (don't know if this happened by accident or not).

于 2013-04-15T13:20:03.853 回答
0
  1. 用 '],[' 分割 regn。
  2. 从每个块中删除除数字和逗号之外的任何内容
  3. 用 ',' 分割每个块,限制为 2 个块
  4. 完毕!

var parseRegn = function (regnStr) {  

    var pairs = regnStr.split('],['),                 // 1
        pairStr = '';

    for (var i = 0; i < pairs.length; i++) {

        pairStr = pairs[i].replace(/[^\d|,]/g, '');   // 2

        if (pairStr.length > 0) {
            pairs[i] = pairStr.split(',', 2);         // 3
        }
    }
    return pairs;                                     // 4
};

于 2013-04-16T06:41:54.343 回答
0

带有正则表达式解析的替代版本:

var regn="[1,75],[2,59],[3,66],[4,92],[5,67],[6,77],[7,75],[8,80],[9,67],[10,56],[11,67],";
var rez = [];
var regex = /\[(\d+),(\d+)\]/g;
var match;
while ((match = regex.exec(regn)) != null) {
    rez.push([match[1], match[2]]);
}

graphData.data = rez;
于 2013-04-15T13:42:22.297 回答
0

代替

var regn="[1,75],[2,59],[3,66],[4,92],[5,67],[6,77],[7,75],[8,80],[9,67],[10,56],[11,67],"

尝试这个,

var regn=[[1,75],[2,59],[3,66],[4,92],[5,67],[6,77],[7,75],[8,80],[9,67],[10,56],[11,67]];

var graphData = [{
            data: regn,
            color: '#77b7c5',
            points: { radius: 4, fillColor: '#77b7c5' }
        }
    ];
于 2013-04-15T13:45:25.057 回答