var x = null;
+++x
生成一个 ReferenceError
,但是当我使用后缀增量运算符 +x++
执行相同操作时,它工作得很好。
最佳答案
++
运算符的 LeftHandSideExpression
不能是数字。例如
1++;
将失败并出现相同的错误(无效的增量操作数)。您只能对变量/标识符/表达式应用前置和后置增量运算符。
由于 +
符号将 null 值
转换为数字 (0),因此您得到了相同的结果。
例子:
var foo = null,
bar = 5;
foo++; // 0
0++; // invalid increment operand
null++; // invalid increment operand
(+bar)++ // invalid increment operand
foo++ +2; // 2
关于javascript - 为什么当 +x++ 工作正常时,+++x 会给出错误消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7715585/