js关于操作符

直接上代码

var num = '123';
console.log( ++num );

输出124我能理解

console.log( ++'123' );

报错Uncaught ReferenceError: Invalid left-hand side expression in prefix operation

为什么只是一个是存入变量就不会报错 一个是直接暴露出来 就报错

阅读 3.5k
4 个回答

你搞错了自增/自减符号的运算意义
它们的共同点是,把自身+1或者是-1之后的值赋值给自己,注意,是要把结果赋值给自己的。
那么你弄个常量来进行自增自减怎么可能不报错……

规范在这里,你可以参考一下:

UnaryExpression : ++ UnaryExpression

  1. Let expr be the result of evaluating UnaryExpression.

  2. Let oldValue be ToNumber(GetValue(expr)).

  3. ReturnIfAbrupt(oldValue).

  4. Let newValue be the result of adding the value 1 to oldValue, using the same rules as for the + operator (see 12.7.5).

  5. Let status be PutValue(expr, newValue).

  6. ReturnIfAbrupt(status).

  7. Return newValue.

PostfixExpression : LeftHandSideExpression ++

  1. Let lhs be the result of evaluating LeftHandSideExpression.

  2. Let oldValue be ToNumber(GetValue(lhs)).

  3. ReturnIfAbrupt(oldValue).

  4. Let newValue be the result of adding the value 1 to oldValue, using the same rules as for the + operator (see 12.7.5).

  5. Let status be PutValue(lhs, newValue).

  6. ReturnIfAbrupt(status).

  7. Return oldValue.

自增,在包含有效数字的字符串时,先将其转换为数字值,再执行加1。
自增操作符只能操作 变量 ,直接跟数字是要报错的。

++num =>  num = num + 1

++'123' =>  '123' = '123' + 1 ?

++和--以及赋值运算符操作的都是内存空间里面的值,如果一个值不存在内存空间那么则报错,而js会给变量,对象属性,数组元素开辟内存空间,这几个类型的直接量都被称作为左值。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题