number(x) 和 parseFloat(x) 哪个更好? [英] Which is better, number(x) or parseFloat(x)?
问题描述
哪个更好?
我问这个只是为了减少几个字节,因为我可以使用 +x 而不是 number(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
会截断字符串中的数字,而 Number
给出 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
但是 Number
对于空字符串或只包含空格的字符串表现得很奇怪:
But Number
acts weird with empty strings or strings containing only white space:
parseFloat(''); // => NaN
Number(''); // => 0
parseFloat('
'); // => NaN
Number('
'); // => 0
总的来说,我觉得Number
更合理,所以我个人几乎总是使用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.
这篇关于number(x) 和 parseFloat(x) 哪个更好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!