简体   繁体   English

使用函数设置JavaScript对象的值

[英]Set JavaScript Object value with a function

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. 本质上,im会尝试计算对象中某个特定点之前的总值,这是传递给calculateTotal函数的limit变量im。

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! 谢谢!

The value of the total member is getting set to the function you have defined, not it's return value. total成员的值将设置为您定义的函数,而不是返回值。

As @Santi points out, we can't reference v inside calculateTotal until v has finished being declared. 正如@Santi指出的那样,在v声明完成之前,我们无法在calculateTotal引用v

An approach here could be to populate total after v has been declared like this: 这里的一种方法可能是在这样声明v后填充total

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);

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 . 乔纳森(Jonathan)的回答简洁明了,但是我认为我会使用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); vf = 100; console.log("f changed to 100"); console.log("v.total = " + v.total); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM