开发者

+= works but ++

开发者 https://www.devze.com 2023-03-27 16:22 出处:网络
In my Javascript code += increments the number but ++ doesn\'t. Could somebody explain why? Doesn\'t increment

In my Javascript code += increments the number but ++ doesn't. Could somebody explain why?

Doesn't increment

words[splitted[i]] = ( typeof words[splitted[i]] != 'undefined' ) 
                       ? words[splitted[i]]++ 
                       : 1

Does increment

words[splitted[i]] = ( typeof words[splitted[i]] != 'undefined' ) 
                       ? word开发者_开发知识库s[splitted[i]] += 1 
                       : 1

Sample code is here


Try moving the ++ to the left side.

var number = 1;
number = ++number;
>>> 2

The reason the position of the ++ makes a difference, is because on the right side, you're doing an assignment, then an increment of the right hand side value. When the operator is on the left, you're doing an increment then assignment.


Your code, in a simpler form, will potentially result in code of this form when words[splitted[i]] is defined:

x = x++;

x++ returns the value of x, and then increments it, and then sets the value returned to x. This contrasts with

x = ++x;

where x is incremented first and then evaluated.

To see how this works, look at the following code:

x = 1;
y = 1;
z = 1;
x = x++;
y = ++y;
z = z += 1;
alert(x); // 1
alert(y); // 2
alert(z); // 2

In any case, I think what you are really wanting to do is something along these lines:

(typeof words[splitted[i]] !== 'undefined') ? 
    words[splitted[i]]++ : 
    words[splitted[i]] = 1;

This is more lines, but might be more readable:

if (typeof words[splitted[i]] !== 'undefined') {
  words[splitted[i]] = 0
}
words[splitted[i]]++;


http://www.w3schools.com/js/js_operators.asp, - check the ++ operator section

x=++y -> x=6, y=6
x=y++ -> x=5, y=6
0

精彩评论

暂无评论...
验证码 换一张
取 消