Post-increment operator does not increment variable until after evaluation [duplicate]

房东的猫 提交于 2021-02-05 12:17:21

问题


I am searching for a reason for why increment operator doesn't increment the numeric value in the place where I set the innerHTML value, like below:

<div id="php"></div>

var a = 14;
document.getElementById("php").innerHTML = a++;//the result will be 14 instead of 15

回答1:


It does increase the variable, however it writes to the innerHTML then increments the value, You could use ++a which will increase the value before it writes to the innerHTML.

var a = 14
var b = 14
console.log('before a', a)
document.getElementById("test1").innerHTML = a++
console.log('after a', a)

console.log('before b', b)
document.getElementById("test2").innerHTML = ++b
console.log('after b', b)
<div id="test1"></div>
<div id="test2"></div>



回答2:


Instead of using a++ you can do ++a to get the increment before the variable value assignation:

var a = 14;
document.getElementById("php").innerHTML = ++a;
<div id="php"></div>



回答3:


Because you use the postfix increment operator variable++, that means you get the value first and then the variable is incremented.

When you use prefix increment operator ++variable, the variable gets incremented first and then the value is returned.

var a = 42;
console.log(a++); // shows 42, value is 43
console.log(a);   // 43
console.log(++a); // 44
console.log(a);   // 44


来源:https://stackoverflow.com/questions/40950766/post-increment-operator-does-not-increment-variable-until-after-evaluation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!