简体   繁体   English

加上等于操作员每次增加价值

[英]Plus equals operator to increase value each time

I am sure this is very simple but I can't get seem to get this to work just right. 我确信这很简单,但我似乎无法让这个工作得恰到好处。 Here is my code: 这是我的代码:

var zero = 10;

function some(elem, num) {
    return elem += num;
}

console.log(some(zero, 10));
console.log(some(zero, 10));
console.log(some(zero, 10));

From what I understand, I was expecting the variable in zero to increase each time by 10.. So, it would be 10, 20 and 30. Instead, I keep getting 10. Obviously, this isn't right. 根据我的理解,我期待zero变量每次增加10 ..所以,它将是10,20和30.相反,我一直得到10.显然,这是不对的。

My question is, how would I increase the variable zero by 10 each time and save that value back to the variable zero ? 我的问题是,我如何每次将变量zero增加10并将该值保存回变量zero

JavaScript passes by value, so modifying the passed value won't have any effect on the caller's variable. JavaScript按值传递,因此修改传递的值不会对调用者的变量产生任何影响。 You'd need to use the return value: 您需要使用返回值:

var zero = 10;

function sum(elem, num) {
    return elem + num;
}

console.log(zero = sum(zero, 10));
console.log(zero = sum(zero, 10));
console.log(zero = sum(zero, 10));

When you do 当你这样做

elem += num

...in your function, you're incrementing the value held by the elem argument passed to the function, not the variable that argument's value came from. ...在你的函数中,你正在递增传递给函数的elem参数所持有的值, 而不是参数值来自的变量。 There is no link between the argument elem and the variable zero , the value of zero , as of the call to some , gets passed into the function. 有论点之间没有联系elem和变量zero zero ,作为调用的some ,被传递给函数。

Primitives like number are passed by value not by reference. 像数字这样的原语是通过值而不是通过引用传递的。 It means that you increment the local elem variable, not the zero ones. 这意味着你增加了本地elem变量,而不是zero变量。 So, you need – outside the function – to reassign zero after each call of the function: 因此,您需要 - 在函数外部 - 在每次调用函数后重新分配zero

console.log(zero = some(zero, 10));

Or, makes zero a property of an object, an pass the object. 或者,将零作为对象的属性,传递对象。 Objects are passed by reference, and not value. 对象通过引用传递,而不是值。 So, for instance: 所以,例如:

var zero = [10]

function some(elem, num) {
    return elem[0] += num;
}

console.log(some(zero, 10));
console.log(some(zero, 10));
console.log(some(zero, 10));

That's because zero nows is not a primitive, but an Array, and arrays are objects and therefore passed by reference. 这是因为zero不是原始数据,而是数组,数组是对象,因此通过引用传递。

Try this: 尝试这个:

sum = (function sum(num){
    var zero = 0;
    return function () {
        return zero += num;
    };

})(10);

console.log(sum());
console.log(sum());
console.log(sum());

zero = some(zero, 10)

You return the new value in some(). 您在some()中返回新值。 So you have to assign it to zero after the function call. 所以你必须在函数调用后将它赋值为零。

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

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