views:

46

answers:

3

Consider the two implementations below,

data.addRows([
  ['2004', 1000],
  ['2005', 1170],
  ['2006', 660],
  ['2007', 1030]
]);

The above works (ie) it gets me what i want.

and my implementation is,

 for (var i = 0; i < 10; i++) {
        data.addRows['row'+i,i];
    }

Is this a valid for loop or what am i doing wrong?

I am using google visualization api for drawing charts but the answers below doesn't work out,

http://jsbin.com/okafa3/edit which is a copy of http://code.google.com/apis/visualization/documentation/gallery/areachart.html

<html>
  <head>
    <script type="text/javascript" src="http://www.google.com/jsapi"&gt;&lt;/script&gt;
    <script type="text/javascript">
      google.load("visualization", "1", {packages:["corechart"]});
      google.setOnLoadCallback(drawChart);
      function drawChart() {
        var data = new google.visualization.DataTable();
        data.addColumn('string', 'Year');
        data.addColumn('number', 'Sales');


       for (var i = 0; i < 10; i++) {
        data.addRows(['row'+i,i]);
    }

          var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
        chart.draw(data, {width: 400, height: 240, title: 'Company Performance',
                          hAxis: {title: 'Year', titleTextStyle: {color: '#FF0000'}}
                         });
      }
    </script>
  </head>
  <body>
    <div id="chart_div"></div>
  </body>
</html>​
+3  A: 

You're missing the parenthesis of the function call:

 for (var i = 0; i < 10; i++) {
        data.addRows(['row'+i,i]);
    }
nico
@nico oh my god how could i missed that. Anyhow thanks for pointing it out.
Pandiya Chendur
at least your for loop is valid :)
Stefanvds
@Pandiya Chendur: no worries, things like that happen. You're looking so hard to find some obscure error that you don't notice obvious mistakes :)
nico
+2  A: 

It seems your method addRows needs an array of [string, int]. Thus you'll need to do:

for (var i=0; i<10; i++) {
   data.addRows(   // parenthesis for calling a method
      [            // array of
           ['row'+i,i] // [string, int] even if it's only one
      ]);

(Spaces and enters added for clarity)

helios
+3  A: 

The exact equivalent code would be

var rows = [];
for (var i=0; i<10; i++) {
   rows.push(['row'+i, i]);
}
data.addRows(rows);

What helios had suggested would also work except it is not exact representation of earlier code as it would make more than one call to data.addRows.

VinayC