Im trying to set an Object value with a function.
essentially, im trying to calculate the total values in an object up to a certain point, which is the limit variable im passing to the calculateTotal function.
seems like im doing it wrong, any suggestions?
var sc = 0.75
com = 2197.63,
user_input = 400,
f11_total = 0;
var v = {
"a": com,
"b": (com * 0.06 * sc),
"c": (com * 0.09 * sc),
"d": (215.54 * Math.pow(sc, 2)),
"e": (299.36 * sc),
"f": 328.76,
"g": ((com * 0.048) * (user_input / 400)),
"h": (com * 0.01),
"3.6": 0.036,
"total": function() {
calculateTotal(3.6);
}
};
function calculateTotal(limit) {
for (var k in v) {
if (k == limit) return (f11_total * v[k]);
f11_total += v[k];
}
}
console.log(calculateTotal(3.6));
thanks!
2 Answers 2
The value of the total member is getting set to the function you have defined, not it's return value.
As @Santi points out, we can't reference v inside calculateTotal until v has finished being declared.
An approach here could be to populate total after v has been declared like this:
var v = {
"a": com,
"b": (com * 0.06 * sc),
"c": (com * 0.09 * sc),
"d": (215.54 * Math.pow(sc, 2)),
"e": (299.36 * sc),
"f": 328.76,
"g": ((com * 0.048) * (user_input / 400)),
"h": (com * 0.01),
"3.6": 0.036
};
v.total = calculateTotal(3.6);
5 Comments
undefined result, what am i missing?116.88649793999998, however the example above will return 0. And k == limit will always evaluate to true. It's the property before "total".v is undefined because you're referencing v inside it's own initialization.k == limit is true (and i check, it returns true just once), the function is suppose to return 116.886... if i call the function from outside the object, it works fine.The primary issue is that you're returning a function instead of an actual value.
Jonathan's answer is concise and correct, however I figured I'd supply you with a modern alternative using get.
It requires no manipulation/initialization of the object, is entirely self-contained, and will recalculate if/when the object is modified.
var sc = 0.75
com = 2197.63,
user_input = 400;
var v = {
"a": com,
"b": (com * 0.06 * sc),
"c": (com * 0.09 * sc),
"d": (215.54 * Math.pow(sc, 2)),
"e": (299.36 * sc),
"f": 328.76,
"g": ((com * 0.048) * (user_input / 400)),
"h": (com * 0.01),
"3.6": 0.036,
get total() {
var f11_total = 0;
for (var k in this) {
if (k == 3.6) return (f11_total * this[k]);
f11_total += this[k];
}
}
}
console.log("v.total = " + v.total);
v.f = 100;
console.log("f changed to 100");
console.log("v.total = " + v.total);
"total": calculateTotal(3.6)get. I realize this question is "complete" but decided to throw an alternative in the ring anyway.