为什么Javascript先加1再减去,再减去1再加?

时间:2019-02-01 14:48:18

标签: javascript

我正在尝试创建一个小的Javascript程序,当我单击“ +”按钮时加1,而当我单击“-”按钮时减1。它可以正常工作,但是当我加1然后去减去1时,先单击“-”按钮,然后再减去一个。

例如。 1,2,3,4,(然后单击“-”按钮)5,4,3 ...

   var number = 1;
<button type="button" onClick="document.getElementById('number').innerHTML = number++">+</button>
<button type="button" onClick="document.getElementById('number').innerHTML = number--">-</button>
<div id="number"></div>


 

2 个答案:

答案 0 :(得分:3)

这基本上是因为您正在做number++,而您应该做++number

var number = 0;
<button type="button" onClick="document.getElementById('number').innerHTML = ++number">+</button>
<button type="button" onClick="document.getElementById('number').innerHTML = --number">-</button>
<div id="number"></div>

了解发生了什么you need to know the following

a++将返回a,然后执行++操作。

++a将返回对++执行a操作的结果。

var a = 5;
var b = 8;

console.log(a++) // will show 5.
console.log(a) // will show 6, because the ++ operation was executed.

console.log(++b) //will show 9. because the ++ operation was executed.
console.log(b) // will keep showing 9.

答案 1 :(得分:0)

++ number将递增number的值,然后返回递增的值。

var number=1;
<button type="button" onClick="document.getElementById('number').innerHTML = ++number">+</button>
<button type="button" onClick="document.getElementById('number').innerHTML = --number">-</button>
<div id="number"></div>

number ++会增加number的值,但会返回我在增加之前持有的原始值。

var number =1;
<button type="button" onClick="document.getElementById('number').innerHTML = number++">+</button>
<button type="button" onClick="document.getElementById('number').innerHTML = number--">-</button>
<div id="number"></div>