Javascript: parseFloat not working -


i using jquery pull data web page, comes array following values (.5, .25, 1.25, 3.75) trying add. here's code snippet:

var th = 0;     (thisrow in objgrid) {         var hours = objgrid[thisrow]['hours'];         th = th+parsefloat(hours);         console.log(hours);          $("#msgbox").html("showing records week: " + thisdate + ". total hours week : " + th);    } 

in console.log getting hours - 0, 0 , 1, 3 , totaling 4. if don't use parsefloat still same results, (thought nan). doing wrong?

i think must have other problem, describing should work. example (here's bad-but-direct translation of code):

var grid = [ ".5", ".25", "1.25", "3.75" ]; var th = 0; (x in grid){   var h = grid[x];   var hrs = parsefloat(h);   th = th + hrs;   console.log( h, hrs ); } //   .5 0.5 //  .25 0.25 // 1.25 1.25 // 3.75 3.75  console.log( th ); // 5.75 

a few things should change code anyhow:

  1. don't use for ( x in ) iterate on array; use numeric loop: for (var i=0,len=a.length;i<len;++i)

  2. always var variables. you're using , overwriting global thisrow variable. when use for ... in, for (var x in o) (unless have declared variable earlier in function).

  3. you should use th += ... instead of th = th + ..., because it's shorter , dryer.

  4. you should use *1 instead of parsefloat. it's faster, less typing, , doesn't lie when have janky string.


Comments

Popular posts from this blog

javascript - Enclosure Memory Copies -

php - Replacing tags in braces, even nested tags, with regex -