Austen Novis
Austen Novis

Reputation: 444

having problems with for loop in javascript

I have a table with numbers but they are stored as string so I am trying to use the function parseFloat to convert it into a table of ints. However, no matter how I do the for loops it gives me a blank table. I can parse the row and it will give me a single int. I can parse a single int as well but cant seem to parse a row or the table. here is what I have so far. This is just trying to convert one row. I tried two for loops for the entire table but that didn't work either. thanks.

 var c =[];
    var entries = $.parseJSON('<?php print(json_encode($try, true)); ?>');  
       for (var j = 0; j < 12; j++)
       {
         for (var i = 0; i < 7; i++)
         { 
         c [j][i] = parseFloat(entries[j][i]);
         }
       }
alert(c);

here is entries json encodes [["-248","-163","-455","-1413","-1294","-1296","-1089"],["-172","-219","-1186","-1368","-1480","-1079","-845"],["-98","-198","-703","-996","-1100","-585","-616"],["-116","-241","-498","-642","-704","-354","-430"],["-137","-117","-264","-525","-533","-269","-476"],["-12","87","-257","-463","-551","-302","-535"],["170","61","-250","-472","-659","-220","-605"],["159","96","-234","-513","-617","-196","-710"],["185","117","-272","-521","-610","-258","-798"],["208","95","-234","-534","-696","-280","-854"],["192","151","-188","-641","-739","-279","-957"],["249","223","-235","-684","-763","-339","-978"]]

Upvotes: -1

Views: 70

Answers (2)

Derek
Derek

Reputation: 2735

In your first loop for (var j = 0; i < 12; j++), you are using i for iteration but it is undefined and it should be j instead of i

var c =[];
var entries = $.parseJSON('<?php print(json_encode($try, true)); ?>');  
for (var j = 0; j < entries.length ; j++)
{
    c[j] = [];
    for (var i = 0; i < entries[i].length ; i++)
    {          
       c [j][i] = parseFloat(entries[j][i]);
    }
}

Upvotes: 0

jfriend00
jfriend00

Reputation: 707158

You have to initialize the second dimension of your array to also be an array. As it stands now, c[j] is just a single value so you can't do c[j][i] on it. There is also an error in your first for loop where you need to compare the value of j, not i. See this fixed code:

var c = [];
var entries = $.parseJSON('<?php print(json_encode($try, true)); ?>');  
   for (var j = 0; j < 12; j++)
   {
     c[j] = [];
     for (var i = 0; i < 7; i++)
     { 
         c [j][i] = parseFloat(entries[j][i]);
     }
   }
alert(c);

Upvotes: 3

Related Questions