javascript - 使用 + 作为转换机制是如何工作的?

标签 javascript string casting type-conversion typeof

我见过使用加号运算符将字符串转换为数字的代码。

这看起来像:

var x ="5",y;
y = +x;
console.log(typeof y) //number

这是如何工作的?

最佳答案

事实上,有两个 + 运算符:二元 + 运算符和这个:一元 + 运算符

看看它是如何描述的in the 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. For example, y = +x takes the value of x and assigns that to y; that is, if x were 3, y would get the value 3 and x would retain the value 3; but if x were the string "3", y would also get the value 3. 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.

关于javascript - 使用 + 作为转换机制是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19296684/

相关文章:

javascript - 尝试将数组从rails传递给javascript

javascript - CSS 样式属性留空

javascript - 无法从子进程获取输出

c# - bool 转换问题的枚举

javascript - 如何在多级数组中选择对象

javascript - 在javascript中将单词拆分为音节

Python:在最后一个小写字母处拆分字符串

C字符串包含模数

c - 关于将 void* 隐式转换为另一种指针类型的 GCC 警告

casting - 参数类型问题