开发者

Variable initialization using increments

开发者 https://www.devze.com 2023-03-08 16:56 出处:网络
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

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

精彩评论

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