开发者

+= works but ++

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜