parseInt vs unary plus - 何时使用哪个 [英] parseInt vs unary plus - when to use which

查看:80
本文介绍了parseInt vs unary plus - 何时使用哪个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这一行之间有什么区别:

What are the differences between this line:

var a = parseInt("1", 10); // a === 1

此行

var a = +"1"; // a === 1

jsperf test 显示一元运算符在当前chrome版本中要快得多,假设它是针对node.js的!?

This jsperf test shows that the unary operator is much faster in the current chrome version, assuming it is for node.js!?

如果我尝试转换不是数字的字符串,则返回 NaN

If I try to convert strings which are not numbers both return NaN:

var b = parseInt("test" 10); // b === NaN
var b = +"test"; // b === NaN

所以我应该何时使用 parseInt 超过一元加(特别是在node.js中)???

So when should I prefer using parseInt over the unary plus (especially in node.js)???

编辑:和有什么不同双波浪形运算符 ~~

edit: and what's the difference to the double tilde operator ~~?

推荐答案

请参阅这个答案了解更完整的案例












嗯,这里有一些我所知道的差异:

Please see this answer for a more complete set of cases




Well, here are a few differences I know of:


  • 空字符串评估为 0 ,而 parseInt 将其评估为 NaN 。 IMO,一个空白字符串应该是 NaN

  • An empty string "" evaluates to a 0, while parseInt evaluates it to NaN. IMO, a blank string should be a NaN.

+'' === 0;              //true
isNaN(parseInt('',10)); //true


  • 一元 + 更像 parseFloat ,因为它也接受小数。

  • The unary + acts more like parseFloat since it also accepts decimals.

    parseInt 另一方面当它看到非数字字符时会停止解析,例如预期的时间段小数点

    parseInt on the other hand stops parsing when it sees a non-numerical character, like the period that is intended to be a decimal point ..

    +'2.3' === 2.3;           //true
    parseInt('2.3',10) === 2; //true
    


  • parseInt parseFloat 从左到右解析并构建字符串 。如果他们看到无效字符,则返回已解析的内容(如果有)作为数字,如果没有解析为数字,则返回 NaN

  • parseInt and parseFloat parses and builds the string left to right. If they see an invalid character, it returns what has been parsed (if any) as a number, and NaN if none was parsed as a number.

    另一方面,一元 + 将返回 NaN 如果整个字符串不可转换为数字。

    The unary + on the other hand will return NaN if the entire string is non-convertible to a number.

    parseInt('2a',10) === 2; //true
    parseFloat('2a') === 2;  //true
    isNan(+'2a');            //true
    


  • @Alex K. parseInt parseFloat 将按解析字符。这意味着十六进制和指数表示法将失败,因为 x e 被视为非数字组件(至少在base10)。

  • As seen in the comment of @Alex K., parseInt and parseFloat will parse by character. This means hex and exponent notations will fail since the x and e are treated as non-numerical components (at least on base10).

    一元 + 会正确转换它们。

    parseInt('2e3',10) === 2;  //true. This is supposed to be 2000
    +'2e3' === 2000;           //true. This one's correct.
    
    parseInt("0xf", 10) === 0; //true. This is supposed to be 15
    +'0xf' === 15;             //true. This one's correct.
    


  • 这篇关于parseInt vs unary plus - 何时使用哪个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆