如何从包含数组的字符串向Javascript DataTable添加行?

时间:2016-04-19 16:54:44

标签: javascript charts google-visualization

我正在尝试制作一个Google图表,用于从网页上的隐藏字段中提取数据。

如果我直接通过data.addRows添加数据,它可以正常工作:

google.charts.load('current', {packages: ['corechart', 'line']});
google.charts.setOnLoadCallback(drawChart);

function drawChart() {
      var data = new google.visualization.DataTable();
      data.addColumn('date', 'Date');
      data.addColumn('number', 'Rainfall');     

      data.addRows([[new Date(2000, 8, 5), 56], [new Date(2000, 8, 6), 22], [new Date(2000, 8, 7), 44], [new Date(2000, 8, 8), 40], [new Date(2000, 8, 9), 62]]);

      var options = {
        title: 'Rainfall'
      };

      var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
      chart.draw(data, options);
    }

但是,如果我尝试创建一个包含该数组的字符串,然后使用addRows添加它,则它不起作用:

google.charts.load('current', {packages: ['corechart', 'line']});
google.charts.setOnLoadCallback(drawChart);

function drawChart() {
      var data = new google.visualization.DataTable();
      data.addColumn('date', 'Date');
      data.addColumn('number', 'Rainfall');     

      var myData = "[[new Date(2000, 8, 5), 56], [new Date(2000, 8, 6), 22], [new Date(2000, 8, 7), 44], [new Date(2000, 8, 8), 40], [new Date(2000, 8, 9), 62]]"

      data.addRows(myData);

      var options = {
        title: 'Rainfall'
      };

      var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
      chart.draw(data, options);
    }

如何将字符串中的数据添加到DataTable?

JSFiddle:https://jsfiddle.net/oo5w6ghf/4/

1 个答案:

答案 0 :(得分:1)

想出来 - 我需要在字符串中添加“eval”:

 var myData = eval("[[new Date(2000, 8, 5), 56], [new Date(2000, 8, 6), 22], [new Date(2000, 8, 7), 44], [new Date(2000, 8, 8), 40], [new Date(2000, 8, 9), 62]]")