为什么+"1"返回一个整数?

3
return "1";  // returns string
return +"1"; // returns int

我想知道使用“+n将字符串转换为整数的方法被称为什么。

因为在这种情况下,+ 被解释为“使该值为正”的操作。 “负字符串”不存在,因此字符串-1被强制转换为int类型。 如果您使用 return -"1",也不会有任何区别,只是您会得到一个负数。 - Marc B
尝试添加一个+"1"的注释,被质量过滤器拒绝了 - BoltClock
4个回答

5

这只是根据语言规范执行的一元+运算符进行的内在类型强制转换。

  1. expr成为评估UnaryExpression的结果。
  2. 返回ToNumber(GetValue(expr))。

因此,虽然概念上它只是一元-的相反,但由于+操作只意味着“乘以正数1”,所以真正做的工作就是将值强制转换为数字。


4

来自于MDN:

Unary plus (+)

The unary plus operator precedes its operand and evaluates to its operand but attempts to converts it into a number, if it isn't already. Although unary negation (-) also can convert non-numbers, unary plus is the fastest and preferred way of converting something into a number, because it does not perform any other operations on the number. It can convert string representations of integers and floats, as well as the non-string values true, false, and null. Integers in both decimal and hexadecimal ("0x"-prefixed) formats are supported. Negative numbers are supported (though not for hex). If it cannot parse a particular value, it will evaluate to NaN.

Examples:

+3     // 3
+"3"   // 3
+true  // 1
+false // 0
+null  // 0

1
这是从https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators中提取的,但由于某种原因,将句子分成了段落。 - BoltClock
1
"从https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Unary_plus_(.2B)抄袭。抄袭的文本应放在引用块中,并应链接到来源。" - Josh Crozier
2
不要回避问题。你需要引用你的来源。这是一个规则。请参见http://meta.stackexchange.com/questions/160077/users-are-calling-me-a-plagiarist-what-do-i-do。 - BoltClock
@CatalinMunteanu 不,我认为这不是问题,只需引用来源即可。否则会给人一种你试图隐藏这些信息的印象,尽管这可能并非事实。 - axelduch

1
你正在使用一元运算符+,它会尝试将其右侧的任何内容转换为数字(作为浮点数)。
请注意,如果无法转换为数字,它可能返回NaN
同样地,你可以使用parseFloat,它也可能返回NaN
parseFloat(anyValue, 10); 

0

您正在应用一元运算符+

对于字符串来说,它没有定义,因此JS必须先将字符串转换为数字。

当然,要小心不要意外地将其变成二元运算符。这不是您想在实际代码中使用的东西,因为它有点脆弱 :)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接