A JavaScript language problem
In the following example
<!DOCTYPE html>
<meta charset="utf-8">
<title>Untitled Document</title>
<script>
var str = '11';
str = str++;
alert(str); // 11
</script>
why is the result 11
and not 12
?
In th开发者_运维知识库is example the result is 12
:
<!DOCTYPE html>
<meta charset="utf-8">
<title>Untitled Document</title>
<script>
var str = '11';
str++;
alert(str); // 12
</script>
Why is this so?
Thank you!
var str = 10;
var re = str++;
alert(re); // 10
alert(str); // 11
str
will return 10 to re
first, and then increments str
itself to 11.
But
var str = 10;
var str = str++;
alert(str); // 10
In this case, str
return 10 to str
first, and then str
should increments str
itself to 11.
But it doesn't. Can anyone explain this?
Thank you!
The reason why this happens is because the return value of a post increment (str++
) is the value before incrementing.
Example:
var x = 10;
alert(x++); //10, because return value is value before increment
alert(x); //11 because the variable was incremented on the previous line
The way to solve this issue is to use the pre-increment operator, which is simply the ++
operator before its operand (++str
). This will add 1 to the operand and return the new value - as opposed to the post-increment operator (str++
) which will add 1 to operand and return the old value.
Example:
var x = 10;
alert(++x); //11
By the way, the statement str = str++
is a real gotcha. The reason why:
The expression str++
returns the original value, so when you reassign it to str
, you are essentially re-assigning the OLD VALUE back into str
. Hence zero mutation to the variable and you are back at square one.
Here's how your code should look like:
<!DOCTYPE html>
<meta charset="utf-8">
<title>Untitled Document</title>
<script>
var str = '11';
alert(++str); // 12
</script>
The expression with the ++
operator first evaluates to 11 and then increments the value of str
.
Try ++str
. It will return 12.
精彩评论