javascript - js关于操作符
PHP中文网
PHP中文网 2017-04-11 12:39:25
[JavaScript讨论组]

直接上代码

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

输出124我能理解

console.log( ++'123' );

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

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

PHP中文网
PHP中文网

认证0级讲师

全部回复(3)
迷茫

你搞错了自增/自减符号的运算意义
它们的共同点是,把自身+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。
自增操作符只能操作 变量 ,直接跟数字是要报错的。

ringa_lee
++num =>  num = num + 1

++'123' =>  '123' = '123' + 1 ?
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号