开发者

Variable initialization using increments

is it possible to initialize a variable by incrementing it? Here's an example of what i mean:

In this example, x has not been initialized yet

>x += 1

>开发者_C百科;print(x)

1


No, that code is not guaranteed to work in all ECMAScript (JavaScript) interpreters.

Most engines should throw a ReferenceError, saying "x is not defined". Even a permissive interpreter that might declare x automatically for you would define it as "undefined" and undefined + 1 is NaN, not 1.


No. That's not possible in JavaScript. Variables must be declared before they can be used / incremented.


var x = ++x || 1;

  1. On the initial run, x is undefined, first part of the OR will be false, though the second one will be used.
  2. On any consecutive run the first part of OR will be used, while the second one will be ignored.
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜