admin管理员组文章数量:1434949
I have something like var num = 10;
and I'm trying to get the sum of this number added to itself on a click function.
So it will be 10
; then on click: 20
; and on another click: 30
; and 40
; etc...
Using ++
gives me 11
, 12
, ... and adding the var to itself is 10
, 20
, 40
, 80
,...
I have something like var num = 10;
and I'm trying to get the sum of this number added to itself on a click function.
So it will be 10
; then on click: 20
; and on another click: 30
; and 40
; etc...
Using ++
gives me 11
, 12
, ... and adding the var to itself is 10
, 20
, 40
, 80
,...
4 Answers
Reset to default 2If you add the variable to itself without storing its original value somewhere, you can't keep adding that value because it has been forgotten.
let x = 10;
let originalX = x;
x += originalX; // 20
x += originalX; // 30
x += originalX; // 40
You're looking for the addition assignment operator aka +=
:
var display = document.querySelector('#txtDisplay');
var btn = document.querySelector('#btnIncrement');
let i = 10;
display.setAttribute('value', i);
//calling will increase the value of i by whatever is passed to the outer most function (in this case, the original value of i)
const increment = (function(amount) {
return function() {
i += amount;
}
}(i));
btn.addEventListener('click', () => {
increment();
display.setAttribute('value', i);
});
<label>Current value:
<input id="txtDisplay" type="text" readonly="readonly"/>
</label>
<input id="btnIncrement" type="button" value="Increment" />
You need to use Addition Assignment
operator +=
var num = 10,
org_num = num;
document.getElementById('inc').addEventListener('click', function() {
num += org_num;
console.log(num);
});
<button id="inc">Increment</button>
Use Closures.
var increment = (() => {
var firstValue, currentValue;
firstValue = currentValue = parseInt(document.getElementById('myValue').innerHTML);
return function(ev) {
currentValue += firstValue;
document.getElementById('myValue').innerHTML = currentValue;
}
})();
<button onclick="increment()">Add my first value.</button>
<p id='myValue'>10</p>
本文标签: javascriptAdding the sum of variable to itselfStack Overflow
版权声明:本文标题:javascript - Adding the sum of variable to itself - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745634869a2667494.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论