Javascript for loop hanging
I am trying to use the Google Charts API to create a chart that has values dynamically given to it. The following code is supposed to take an array of values and populate the chart with them, but is instead hanging and killing the page. I am assuming that the for loop is not ending - but I can't figure out what is wrong.
Any ideas?
<script type="tex开发者_JAVA技巧t/javascript">
google.load("visualization", "1", {packages:["corechart"]});
function drawChart(values) {
var data = new google.visualization.DataTable();
data.addColumn('number', 'Value');
data.addRows(values.length);
for(i=0; i <= values.length; i+3) {
data.setValue(values[i], values[i+1], values[i+2]);
}
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, {width: 400, height: 240, legend: 'none', gridlineColor: '#fff', chartArea:{left:0,top:20}});
}
function stockFractal(){
}
</script>
You are not incrementing the i
variable in the for loop; you want i+=3
not i+3
.
for (i=0; i <= values.length; i+=3)
Problem(s)
You're right that the loop never terminates.
That's because this:
for(i=0; i <= values.length; i+3) {
does not increment i
. It just creates a value which is the result of adding 3
to i
... then discards that value.
It also seems likely that you meant <
, not <=
, since array indexes go from 0
to values.length - 1
.
I also recommend the use of var
.
Solution
Write:
for (var i = 0; i < values.length; i = i + 3) {
or just:
for (var i = 0; i < values.length; i += 3) {
for(i=0; i <= values.length; i+3) {
Should really read:
for(i=0; i <= values.length; i=i+3) {
精彩评论