开发者

Why does +++x gives an error message when +x++ works fine?

var x = null;

+++x generates a ReferenceError, but when I do the same using postfix incremen开发者_如何转开发t operator +x++, it works just fine.


The LeftHandSideExpression for the ++ operator must not be a number. For instance

1++;

will fail with the same error (invalid increment operand). You can only apply the pre- and postincrement operators on variables/identifiers/expressions.

Since the + sign casts the null value into a number (0), you got the same outcome.

Examples:

var foo = null,
    bar = 5;

foo++;    // 0
0++;      // invalid increment operand
null++;   // invalid increment operand
(+bar)++  // invalid increment operand
foo++ +2; // 2


+x++ is split into two steps:

  • +x initialises x to 0, so it's no longer null.
  • x++ then increments x, which works since x is no longer null.

+++x is also split into two steps, but in a particular order:

  • ++x is evaluated first, which throws the exception because x is null.
  • +x would then be evaluated, except you've already had an exception.

I think your assumption was that +++x would be parsed as ++(+x), but it's actually parsed as +(++x). It's an ambiguous-looking syntax, the language designers had to pick one of the two ways to parse it, and from your point of view they chose "the other one".

To be honest, there's absolutely no value in formatting your code this way anyway - all you end up with is dubious-looking code which is destined to confuse people.


if u used the x= 0 ; x will be initalized with a integer type that will accept the ++x operator while ++(+x) is like a ++(+null) so better try to change to X = 0 ;

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜