parseInt vs unary plus,什么时候用哪个?

2022-01-30 00:00:00 node.js javascript

这行有什么区别:

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

还有这一行

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

这个 jsperf 测试 表明一元运算符在当前的 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:和双波浪号运算符~~有什么区别?

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

推荐答案

嗯,这里有一些我知道的区别:

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
    

  • parseIntparseFloat 解析并构建字符串从左到右.如果他们看到无效字符,则返回已解析(如果有)为数字的内容,如果没有被解析为数字,则返回 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 将按字符解析.这意味着十六进制和指数符号将失败,因为 xe 被视为非数字组件(至少在 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).

    一元 + 会正确转换它们.

    The unary + will convert them properly though.

      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.
    

  • 相关文章