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?