javascript - js关于操作符

查看:127
本文介绍了javascript - js关于操作符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

直接上代码

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

输出124我能理解

console.log( ++'123' );

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

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

解决方案

你搞错了自增/自减符号的运算意义
它们的共同点是,把自身+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.

这篇关于javascript - js关于操作符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆