Dar*_*htA 216 javascript string-conversion
parseInt(string)和Number(string)JavaScript有什么区别?
sjn*_*ngm 311
parseInt("123qwe")
Run Code Online (Sandbox Code Playgroud)
返回123
Number("123qwe")
Run Code Online (Sandbox Code Playgroud)
回报 NaN
换句话说,parseInt()解析第一个非数字并返回它解析的任何数字.Number()想要将整个字符串转换为数字,也可以是浮动BTW.
编辑#1:Lucero评论了可以与之一起使用的基数parseInt().就这一点而言,请参阅下面的医生答案(我不打算在此复制,医生应该公平地分享这个名声......).
编辑#2:关于用例:这已经在线之间写了一些.使用Number()的情况下,您间接要检查给定的字符串完全代表一个数值,浮点或整数.parseInt()/parseFloat()不是那么严格,因为它们只是解析并在数值停止时停止(基数!),这使得它在前面需要一个数字值时有用"万一有一个"(注意parseInt("hui")也会返回NaN).最大的区别是使用Number()不知道的基数,并且parseInt()可能从给定的字符串中间接猜测(有时可能会导致奇怪的结果).
THE*_*TOR 69
第一个采用两个参数:
parseInt(string, radix)
Run Code Online (Sandbox Code Playgroud)
radix参数用于指定要使用的数字系统,例如,16(十六进制)的基数表示字符串中的数字应从十六进制数解析为十进制数.
如果省略radix参数,则JavaScript假定以下内容:
您提到的另一个函数只接受一个参数:
Number(object)
Run Code Online (Sandbox Code Playgroud)
Number()函数将object参数转换为表示对象值的数字.
如果该值无法转换为合法数字,则返回NaN.
Ste*_*ith 19
只要字符串以数字字符开头,parseInt(string)就会将包含非数字字符的字符串转换为数字
'10px' => 10
Run Code Online (Sandbox Code Playgroud)
如果字符串包含任何非数字字符,则数字(字符串)将返回NaN
'10px' => NaN
Run Code Online (Sandbox Code Playgroud)
该parseInt函数允许您为输入字符串指定基数,并限制为整数值.
parseInt('Z', 36) === 35
Run Code Online (Sandbox Code Playgroud)
作为Number函数调用的构造函数将使用语法解析字符串,并且仅限于基数10和基数16.
StringNumericLiteral :::
StrWhiteSpaceopt
StrWhiteSpaceopt StrNumericLiteral StrWhiteSpaceopt
StrWhiteSpace :::
StrWhiteSpaceChar StrWhiteSpaceopt
StrWhiteSpaceChar :::
WhiteSpace
LineTerminator
StrNumericLiteral :::
StrDecimalLiteral
HexIntegerLiteral
StrDecimalLiteral :::
StrUnsignedDecimalLiteral
+ StrUnsignedDecimalLiteral
- StrUnsignedDecimalLiteral
StrUnsignedDecimalLiteral :::
Infinity
DecimalDigits . DecimalDigitsopt ExponentPartopt
. DecimalDigits ExponentPartopt
DecimalDigits ExponentPartopt
DecimalDigits :::
DecimalDigit
DecimalDigits DecimalDigit
DecimalDigit ::: one of
0 1 2 3 4 5 6 7 8 9
ExponentPart :::
ExponentIndicator SignedInteger
ExponentIndicator ::: one of
e E
SignedInteger :::
DecimalDigits
+ DecimalDigits
- DecimalDigits
HexIntegerLiteral :::
0x HexDigit
0X HexDigit
HexIntegerLiteral HexDigit
HexDigit ::: one of
0 1 2 3 4 5 6 7 8 9 a b c d e f A B C D E F
小智 6
@ sjngm回答的附录:
他们都忽略了空格:
var foo ="3"; 的console.log(parseInt函数(FOO)); // 3 console.log(Number(foo)); // 3
这不完全正确.正如sjngm写的那样,parseInt 会将字符串解析为第一个数字.是真的.但问题是当你想解析用空格分隔的数字时,即."12 345".在那种情况下parseInt("12 345")将返回12而不是12345.因此,为了避免这种情况,您必须在解析为数字之前修剪空格.我的解决方案是:
var number=parseInt("12 345".replace(/\s+/g, ''),10);
Run Code Online (Sandbox Code Playgroud)
注意我在parseInt()函数中使用的一个额外的东西.parseInt("string",10)将数字设置为十进制格式.如果你要解析像"08"这样的字符串,你会得到0,因为8不是八进制数.解释就在这里
@sjngm 答案的附录:
他们都忽略空格:
var foo = " 3 ";
console.log(parseInt(foo)); // 3
console.log(Number(foo)); // 3
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
91048 次 |
| 最近记录: |