为什么+号是javascript中的例外? [英] why + sign is the exception in javascript?

查看:103
本文介绍了为什么+号是javascript中的例外?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做到了

> 5 + 2 // 7, this is correct 

> 5 - 2 // 3 , obviously 

> 5 - "2" // 3 , ohh, that's awesome 

> 5 % "2" // 1 , :)

> 5 / "2" // 2.5,looks like 2 is automatically converted to integer.Perfect!

> 5 + "2" // "52" Really? 

确定性,带加号的符号正在执行其他操作.那是什么,为什么?

Certainty, something extra is going on with plus sign. What's that and why ?

推荐答案

根据 ECMA 5.1标准规范对于Binary +运算符

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

因此,如果两个操作数中的任何一个均为String类型,则该标准要求实现将两个操作数都转换为字符串类型并将它们连接起来.

So, if either of the operands are of type String, then the standard mandates the implementations to convert both the operands to string type and concatenate them.

注意:,但是一元+运算符的行为与字符串.它将字符串转换为数字.

Note: But the unary + operator behaves differently with strings. It converts the strings to numbers.

1. Let expr be the result of evaluating UnaryExpression.
2. Return ToNumber(GetValue(expr)).

这篇关于为什么+号是javascript中的例外?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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