哪个更好,数字(x)或parseFloat(x)? [英] Which is better, number(x) or parseFloat(x)?
问题描述
哪个更好?
我问这只是为了削减几个字节,因为我可以用+ x而不是数字(x)。 parsefloat会做得更好吗?
I'm asking this just for the sake of shaving a few bytes, as I can use +x instead of number(x). Does parsefloat do something better?
推荐答案
parseFloat和Number
之间的区别 parseFloat
/ parseInt
用于解析字符串,而 Number
/ +
用于将值强制转换为数字。他们的行为不同。但首先让我们看看它们的行为在哪里:
The difference between parseFloat and Number
parseFloat
/parseInt
is for parsing a string, while Number
/+
is for coercing a value to a number. They behave differently. But first let's look at where they behave the same:
parseFloat('3'); // => 3
Number('3'); // => 3
parseFloat('1.501'); // => 1.501
Number('1.501'); // => 1.501
parseFloat('1e10'); // => 10000000000
Number('1e10'); // => 10000000000
因此,只要你有标准数字输入,就没有区别。但是,如果您的输入以数字开头,然后包含其他字符, parseFloat
会截断字符串中的数字,而数字
给出 NaN
(不是数字):
So as long as you have standard numeric input, there's no difference. However, if your input starts with a number and then contains other characters, parseFloat
truncates the number out of the string, while Number
gives NaN
(not a number):
parseFloat('1x'); // => 1
Number('1x'); // => NaN
此外, Number
了解十六进制输入而 parseFloat
不会:
In addition, Number
understands hexadecimal input while parseFloat
does not:
parseFloat('0x10'); // => 0
Number('0x10'); // => 16
但数字
对空字符串的行为很奇怪或仅包含空格的字符串:
But Number
acts weird with empty strings or strings containing only white space:
parseFloat(''); // => NaN
Number(''); // => 0
parseFloat(' \r\n\t'); // => NaN
Number(' \r\n\t'); // => 0
总的来说,我发现数字
更合理,所以我几乎总是亲自使用 Number
(你会发现很多内部JavaScript函数都使用 Number
以及)。如果有人键入'1x'
我更喜欢显示错误而不是将其视为输入'1'
。我真正做出异常的唯一一次是当我将样式转换为数字时,在这种情况下 parseFloat
是有用的,因为样式的形式类似于'3px'
,在这种情况下,我想放弃'px'
部分并获得 3
,所以我在这里找到 parseFloat
。但是你真正选择哪一个取决于你以及你想接受哪种形式的输入。
On the whole, I find Number
to be more reasonable, so I almost always use Number
personally (and you'll find that a lot of the internal JavaScript functions use Number
as well). If someone types '1x'
I prefer to show an error rather than treat it as if they had typed '1'
. The only time I really make an exception is when I am converting a style to a number, in which case parseFloat
is helpful because styles come in a form like '3px'
, in which case I want to drop the 'px'
part and just get the 3
, so I find parseFloat
helpful here. But really which one you choose is up to you and which forms of input you want to accept.
注意使用一元 +
运算符与使用 Number
作为函数完全相同:
Note that using the unary +
operator is exactly the same as using Number
as a function:
Number('0x10'); // => 16
+'0x10'; // => 16
Number('10x'); // => NaN
+'10x'; // => NaN
Number('40'); // => 40
+'40'; // => 40
所以我通常只使用 +
短。只要你知道它的作用,我就会发现它很容易阅读。
So I usually just use +
for short. As long as you know what it does, I find it easy to read.
这篇关于哪个更好,数字(x)或parseFloat(x)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!