return "1"; // returns string
return +"1"; // returns int
我想知道使用“+n”将字符串转换为整数的方法被称为什么。
return "1"; // returns string
return +"1"; // returns int
这只是根据语言规范执行的一元+
运算符进行的内在类型强制转换。
因此,虽然概念上它只是一元-
的相反,但由于+
操作只意味着“乘以正数1
”,所以真正做的工作就是将值强制转换为数字。
来自于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
+
,它会尝试将其右侧的任何内容转换为数字(作为浮点数)。NaN
。parseFloat
,它也可能返回NaN
。parseFloat(anyValue, 10);
您正在应用一元运算符+
。
对于字符串来说,它没有定义,因此JS必须先将字符串转换为数字。
当然,要小心不要意外地将其变成二元运算符。这不是您想在实际代码中使用的东西,因为它有点脆弱 :)
+
被解释为“使该值为正”的操作。 “负字符串”不存在,因此字符串-1被强制转换为int类型。 如果您使用return -"1"
,也不会有任何区别,只是您会得到一个负数。 - Marc B