Am i doing this iteration right in javascript?
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"></script>
<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>
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.
You're missing the parenthesis of the function call:
for (var i = 0; i < 10; i++) {
data.addRows(['row'+i,i]);
}
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)
精彩评论