javascript – 如果我在之前添加但不在之后添加字符串(如“123”)如何转换为数字?

前端之家收集整理的这篇文章主要介绍了javascript – 如果我在之前添加但不在之后添加字符串(如“123”)如何转换为数字?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
当我在“123”之类的引号中添加一个数字之前,它将转换为typeof数字,但如果我添加类似“123”,则它正在等待下一个操作数.为什么?为什么在第一种情况下它转换为数字?

解决方法

在第一种情况下,您使用 Unary plus +

The unary plus operator precedes its operand and evaluates to its operand but attempts to convertit 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 07001.

在第二个你只使用Addition

The addition operator produces the sum of numeric operands or string concatenation.

原文链接:https://www.f2er.com/js/150110.html

猜你在找的JavaScript相关文章