0

I'm getting a behavior that I can't explain or figure out how to fix:

lefts = [{x: 10, y: 20},{x: 30, y: 40},{x: 50, y: 60},{x: 70, y: 80}];

function fnCalcAvg(dims){

    // the purpose of this is to take the lefts array and calculate 
    // the average values for x and y 

    var theSum = {};
    theSum.x = 0;
    theSum.y = 0;

    console.log([theSum.x, theSum.y, theSum]);

    $j(dims).each(function(_k, _v){
        theSum.x += (_v.x * 1);
        theSum.y += (_v.y * 1);
    });


    console.log([theSum.x, theSum.y, theSum]);

    // if I 'return' here, the object values are correct

    theSum.x = parseInt(theSum.x / dims.length);
    theSum.y = parseInt(theSum.y / dims.length);

    console.log([theSum.x, theSum.y, theSum]);

    return theSum;
}

In the first c.log, I get

0, 0, {x: 50, y: 674} // individual values are right, object is not

In the second:

200, 2699, {x: 50, y: 674} // individual values are right, object is not

And in the last:

50, 674, {x: 50, y: 674} // everything is right, but how? Where?

So if I log the individual values of x and y, it's correct, but logging the object, I get values before anything has been assigned.

If I put a return statement before assigning the final values (parseInt...), the object properties are reported correctly.

What's going on here? How can the individual properties be different from the properties shown when logging the object? Is it just a problem with Chrome? Is it a scope issue?

Bill in Kansas City
  • 360
  • 1
  • 5
  • 21
  • I have run your code on the chrome console and the first log prints four zeroes. Where are you running your code?, can you provide a punklr or something similar for reproducibility? – bones.felipe Jun 02 '17 at 01:33
  • 1
    Don't put them in an array, so that Chrome will make a snapshot of them when logging (though inspection will always show the current values) – Bergi Jun 02 '17 at 01:34
  • You should not use `parseInt` on numbers, it's made for strings. What you want is `Math.floor`. – Bergi Jun 02 '17 at 01:35
  • Bergi: removing them from the array in the log statement did the trick. And what I read in the other question (duplicate issue, yes, but not a duplicate question, IMO) tells me that while javascript may be synchronous, that doesn't mean the console necessarily is. (Did the Math.floor, too, thank you.) – Bill in Kansas City Jun 02 '17 at 01:58

0 Answers0