Inline `++` In Javascript Not Working
Astonished to find out that a line like this : $('#TextBox').val(parseInt($('#TextBox').val())++ ); Will not work ! I've done some tests, it plays out to the conclusion that the
Solution 1:
There's nothing particular to jQuery about this. ++
increments a variable. You are trying to increment the return value of a function call.
Solution 2:
Q: What does x++
mean?
A:x++
means take the value of x
, let's call this n
, then set x
to be n + 1
, then return n
.
Q: Why does this fail on a non-variable?
A: Let's try it on something simple, say 3
, and see where things go wrong.
Take the value of
3
and call itn
, okay,n = 3
Set
3
to ben + 1
, so3 = 3 + 1
,3 = 4
this makes no sense! So if this step can't be done, the++
operator can't be used.
Solution 3:
++
works on variables, not directly on numbers
var c = parseInt($('#TextBox').val());
$('#TextBox').val( ++c );
Change the order from
var x = 0;
var result = x++;
result // 0
To
var x = 0;
var result = ++x;
result // 1
Then it will evaluate ++
before retrieving the value.
Post a Comment for "Inline `++` In Javascript Not Working"