[英]How do I add up a number to a properties in my object?
I have an object like this: 我有一个这样的对象:
var statistics = {
won: 0,
tie: 0,
lost: 0
};
I have a function that adds 1 to won
: 我有一个函数,将won
1:
var plus1 = function() {
return statistics.won++;
}
I call that function within an if/else statement like this: 我在if / else语句中这样调用该函数:
plus1();
But it doesn't work. 但这是行不通的。 Does anyone have an idea? 有人有主意吗?
It's probably that x++ returns x instead of x+1. x ++可能返回x而不是x + 1。 You are looking for 你在找
var plus1 = function() {
return ++statistics.won;
}
Looking at your code I don't really see any reason why you would return your result. 查看您的代码,我真的看不出您为什么要返回结果的任何原因。
I would rewrite the function to simply be 我将函数重写为
function plus1() {
statistics.won++;
}
When it comes to having it update, I can't see any were in your code where you actually update the html. 当涉及到更新时,我看不到您的代码中实际更新过html的任何地方。 After you've run plus1(). 运行plus1()之后。 If I run console.log(statistics) in my Console I can see that statistic.won goes up whenever I win. 如果我在控制台中运行console.log(statistics),那么我每次获胜时都会看到statistic.won上升。
As already mentioned in the comment above, if you run wins() after you've run plus1() it will all work. 正如上面的注释中已经提到的,如果在运行plus1()之后运行wins(),那么它将全部正常工作。
This is due to to way pre/post incrementation works in JavaScript: 这是由于JavaScript中的前/后递增方式:
var one = 1;
var two = 1;
// increment `one` FIRST and THEN assign it to `three`.
var three = ++one;
// assign `two` to `four`, THEN increment it
var four = two++;
So in your code, you're assigning the value of statistics.won
to the return
value first and then incrementing it. 因此,在您的代码中,您首先要将statistics.won
的值分配给return
值,然后再将其递增。 You can see the difference in how they work here . 您可以在这里看到它们工作方式的不同 。
So, as I mentioned in the comments, return ++statistics.won;
因此,正如我在评论中提到的, return ++statistics.won;
is the solution you need. 是您需要的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.