在将字符串转换为数字时,parseInt()和Number()的行为如何不同?
当前回答
简介:
方法用于():
Takes a string as a first argument, the radix (An integer which is the base of a numeral system e.g. decimal 10 or binary 2) as a second argument The function returns a integer number, if the first character cannot be converted to a number NaN will be returned. If the parseInt() function encounters a non numerical value, it will cut off the rest of input string and only parse the part until the non numerical value. If the radix is undefined or 0, JS will assume the following: If the input string begins with "0x" or "0X", the radix is 16 (hexadecimal), the remainder of the string is parsed into a number. If the input value begins with a 0 the radix can be either 8 (octal) or 10 (decimal). Which radix is chosen is depending on JS engine implementation. ES5 specifies that 10 should be used then. However, this is not supported by all browsers, therefore always specify radix if your numbers can begin with a 0. If the input value begins with any number, the radix will be 10
数量():
Number()构造函数可以将任何参数输入转换为数字。如果Number()构造函数不能将输入转换为数字,则返回NaN。 Number()构造函数也可以处理十六进制数,它们必须以0x开头。
例子:
console.log(parseInt('0xF', 16)); // 15 // z is no number, it will only evaluate 0xF, therefore 15 is logged console.log(parseInt('0xFz123', 16)); // because the radix is 10, A is considered a letter not a number (like in Hexadecimal) // Therefore, A will be cut off the string and 10 is logged console.log(parseInt('10A', 10)); // 10 // first character isnot a number, therefore parseInt will return NaN console.log(parseInt('a1213', 10)); console.log('\n'); // start with 0X, therefore Number will interpret it as a hexadecimal value console.log(Number('0x11')); // Cannot be converted to a number, NaN will be returned, notice that // the number constructor will not cut off a non number part like parseInt does console.log(Number('123A')); // scientific notation is allowed console.log(Number('152e-1')); // 15.21
其他回答
我总是使用parseInt,但要注意前导零会迫使它进入八进制模式。
parseInt转换为整数,也就是说,它去掉小数。数字不转换为整数。
如果你正在寻找性能,那么最好的结果可能是按位右移“10”>>0。也可以乘(“10”* 1)或not not(~~“10”)。它们都比Number和parseInt快得多。 他们甚至有“feature”为非数字参数返回0。 下面是性能测试。
获得结果的另一种方法是使用~操作符
在大多数情况下
~~someThing === parseInt(something)
但是~~对于parseInt接受的带尾字符的字符串或带基数规范的字符串(例如十六进制)将返回0,并且当parseInt返回NaN时也将返回0。另一个区别是~~如果给定一个bigint,则返回一个你可以添加另一个bigint的bigint,而parseInt如果bigint很大,则返回一个普通的浮点数(是的,它给出的值与parseFloat完全相同)
但是在大多数情况下~~比parseInt快30%。当浮点数表示为字符串时,它只会慢10%。
因此,如果~~的限制范围更适合你的需要,那么就节省使用电脑的时间,减少打字的时间
远离parseInt而使用Number和Math是一个好主意。除非你需要十六进制或八进制。两者都可以使用字符串。为什么要远离它?
parseInt(0.001, 10)
0
parseInt(-0.0000000001, 10)
-1
parseInt(0.0000000001, 10)
1
parseInt(4000000000000000000000, 10)
4
它完全屠杀了大量或少量的人口。奇怪的是,如果这些输入是字符串,它正常工作。
parseInt("-0.0000000001", 10)
0
parseInt("0.0000000001", 10)
0
parseInt("4000000000000000000000", 10)
4e+21
与其冒着很难找到这个错误和人们提到的其他陷阱的风险,我只会避免parseInt,除非你需要解析除10进制以外的东西。数,数学。圆的,数学。和. tofixed(0)都可以做同样的事情,parseInt可以用来没有这些类型的错误。
如果你真的想要或需要使用parseInt来实现它的其他特性,千万不要用它来将浮点数转换为整数。