What does JavaScript interpret `+ +i` as?

时间:2016-10-20 20:12:44

标签: javascript

An interesting thing I've never seen before was posted in another question. They had something like:

var i = + +1;

They thought the extra + converted it to a string, but they were simply adding to a string which is what caused it to convert.

This, however, lead me to the question: what is going on here?

I would have actually expected that to be a compiler error, but JavaScript (at least in Chrome) is just fine with it... it just basically does nothing.

I created a little JSFiddle to demonstrate: Demo

var i = 5;
var j = + +i;
document.body.innerHTML = i === j ? 'Same' : 'Different';

Anyone know what's actually occurring and what JavaScript is doing with this process?

I thought maybe it would treat it like ++i, but i doesn't increment, and you can even do it with a value (e.g., + +5), which you can't do with ++ (e.g., ++5 is a reference error).

Spacing also doesn't affect it (e.g., + + 1 and + +1 are the same).

My best guess is it's essentially treating them as positive/negative signs and putting them together. It looks like 1 == - -1 and -1 == + -1, but that is just so weird.

Is this just a quirky behavior, or is it documented in a standard somewhere?

6 个答案:

答案 0 :(得分:32)

通过AST Explorer发表您的声明,我们可以看到我们在这里得到的是两个嵌套的一元表达式,带有一元+运算符。

这是由++i组成的一元表达式,+i本身是由+i组成的一元表达式。

使用一元+运算符的一元表达式将表达式部分转换为数字。所以你实际上是将i转换为数字,然后再将其结果转换为数字(这是一个无操作)。

为了完成,它可以在您添加的级别上运行:

var i = 5;
console.log(+ + + + + +i); // 5
console.log(i); // still 5

答案 1 :(得分:9)

它在规范中。

通过挖掘,我们可以从§14.6.2.2看到增量和减量运算符在一元运算符之前(并且应该是首选)列出。因此,优先权本身并不能解释这一点。

查看the punctuation table in §11.7,我们可以看到规范中++(运算符)的每个实例都显示了两个实例,没有空格。这不是决定性的,直到你检查......

The whitespace rules in §11.2,具体来说:

  

空格代码点可能出现在StringLiteral,RegularExpressionLiteral,Template或TemplateSubstitutionTail中,它们被视为构成文字值一部分的重要代码点。它们也可能出现在注释中,但不能出现在任何其他类型的令牌中。

JS不允许任意空格中间操作符。

PegJSEsprima中的JS语法证实了这一点,匹配文字的双字符串++

答案 2 :(得分:6)

对我来说非常清楚;

var a = +3;
var b = +a; // same as a, could be -a, for instance
var c = + +a; // same as above, same as +(+a)

答案 3 :(得分:4)

如果您执行++variable,则javascript解释程序会将其视为increment operator

如果您执行+ +variable,则javascript解释程序会将其视为Unary plus,将值强制转换为数字,两次。

所以

var a = 1;
var b = +a;
var c = +b;

console.log(c);// still 1

相同
var c = + +1;

所以简单的答案就是两个加号不能被一个空格分开来解释为增量,这个空间使得解释器看到两个单独的空格,这就是它的真正含义

答案 4 :(得分:2)

+运算符转换为数字,两个+运算符之间有空格,不做任何额外的操作。

答案 5 :(得分:0)

尽管它看起来非常相似,但+ +++与AST解释器完全不同。这同样适用于令牌分离:varfoovar foo不同。

在表达式+ + +i中,每个+都被视为不同的一元运算符,它只是将您的变量转换为数字。对于增量操作,即++,在+和变量令牌之间不允许使用空格。在下面的示例中,最后一行无效:

var x = "4";
console.log(+ + +x);
console.log(+ + ++x);
console.log(+ ++ +x);