Javascript ++与+ = 1 [英] Javascript ++ vs +=1

查看:60
本文介绍了Javascript ++与+ = 1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  var a ="ab";var b ="ab";a + = 1;//"ab1"b ++;//"NaN" 

(在chrome的V8上测试)

有人可以解释为什么基于 ++ 算术运算符和带有参数 1

解决方案

++ 转换为数字,然后递增,并用String连接 + = .

根据规格:

11.3.1后缀增量运算符

   ...
   3.假设 oldValue ToNumber(GetValue(lhs)).
   4.令 newValue 为将值1加到 oldValue 的结果,使用与 + 运算符相同的规则(请参见11.6.3).

对于 a + = 1 情况,如果您向字符串中添加数字,或者相反,则将数字周围的数字转换为字符串:

11.6.1加法运算符(+)

   ...
   7.如果 Type(rprim)是String或 Type(rprim)是String,则
      a.返回是连接ToString(lprim)和ToString(rprim)的结果的字符串

     < 8.返回对ToNumber(lprim)和ToNumber(rprim)应用加法运算的结果.

var a = "ab";
var b = "ab";
a+=1; // "ab1"
b++; // "NaN"

(Tested on chrome's V8)

Can someone explain why the results are different based on the internal atomic actions of the ++ arithmetic operator and the += assignment operator with argument 1

解决方案

++ converts to number, and then increments, += with a String concatenates.

From the spec:

11.3.1 Postfix Increment Operator

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

For the a+=1 case, if you add a number to a string or the other way around the number gets converted to a string:

11.6.1 The Addition operator ( + )

  ...
  7. If Type(lprim) is String or Type(rprim) is String, then
      a. Return the String that is the result of concatenating ToString(lprim) followed by ToString(rprim)

  8. Return the result of applying the addition operation to ToNumber(lprim) and ToNumber(rprim).

这篇关于Javascript ++与+ = 1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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