我问这个只是为了节省几个字节。
我知道我可以用+x(一元加)来代替Number(x)。这些和parseFloat有区别吗?
我问这个只是为了节省几个字节。
我知道我可以用+x(一元加)来代替Number(x)。这些和parseFloat有区别吗?
据我所知,parseFloat稍微快一点,这只是从同事那里听到的,所以可能完全不了解情况。
尽管经过进一步研究,这种性能差异似乎取决于浏览器。
http://jsperf.com/parseint-vs-parsefloat/6
看一下这些jsPerf结果,并做出决定。(它还包括+x个测试)
正如@xdazz的回答所指出的那样,+“”和数字(“”)返回0,而parseFloat(“”)返回NaN,所以我还是会用parseFloat,因为空字符串并不意味着数字0,只有字符“0”的字符串在它意味着0;
不同之处在于当输入不是“固有数”时会发生什么。Number返回NaN,而parseFloat“尽可能多地”解析。如果在空字符串上调用,Number返回0,而parseFloat返回NaN。
例如:
Number("") === 0 // also holds for false
isNaN(parseFloat("")) === true // and null
isNaN(Number("32f")) === true
parseFloat("32f") === 32
在这些例子中,你可以看到区别:
Number('') = 0;
Number(false) = 0;
Number('1a') = NaN;
parseFloat('') = NaN;
parseFloat(false) = NaN;
parseFloat('1a') = 1;
parseFloat稍微慢一点,因为它搜索字符串中数字的第一次出现,而number构造函数则从包含带有空格的数值或包含假值的字符串中创建一个新的数字实例。
parseFloat和Number之间的区别
parseFloat/parseInt用于解析字符串,而Number/+用于将值强制为数字。他们的行为不同。但首先让我们看看它们在哪些地方表现相同:
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(不是一个数字):
parseFloat('1x'); // => 1
Number('1x'); // => NaN
此外,Number理解十六进制输入,而parseFloat不理解:
parseFloat('0x10'); // => 0
Number('0x10'); // => 16
但是对于空字符串或只包含空白的字符串,Number表现得很奇怪:
parseFloat(''); // => NaN
Number(''); // => 0
parseFloat(' \r\n\t'); // => NaN
Number(' \r\n\t'); // => 0
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作为函数完全相同:
Number('0x10'); // => 16
+'0x10'; // => 16
Number('10x'); // => NaN
+'10x'; // => NaN
Number('40'); // => 40
+'40'; // => 40
所以我通常用+来表示。只要你知道它是做什么的,我觉得它很容易读懂。