search

Home  >  Q&A  >  body text

node.js - parseInt 和一元加运算,具体什么时候该用哪个的问题

1. var x = parseInt("1", 10); // x === 1

2. var x = +"1"; // x === 1

我不知道上面两条的区别在哪里,但浏览器测试会发现,一元运算符明显要更快。再试一下,如果是字符串转换(不是数字),两个都会返回 NaN:

1. var y = parseInt("test" 10); // y === NaN

2. var y = +"test"; // y === NaN

所以在 Node.js 中,什么时候该用 parseInt 而不是一元加运算?希望大牛能讲一下其中的区别和原理。

大家讲道理大家讲道理2877 days ago717

reply all(2)I'll reply

  • ringa_lee

    ringa_lee2017-04-17 11:22:27

    parseInt can be used for base conversion.

    Give an example of application: iconfont

    Many websites that generate iconfonts will include hexadecimal font encoding when generating iconfonts, such as 'e800'
    If you don't want to use the before pseudo-element to display the font, you can directly output the converted font encoding in the tag.

        String.fromCharCode(parseInt('\e800',16).toString(10))
    

    You get the real font: ""

    One-yuan plus can connect strings and perform type conversion.

    reply
    0
  • ringa_lee

    ringa_lee2017-04-17 11:22:27

    In fact, they both convert strings into integers. The second one is fast because it directly performs bit operations. But parseInt is not. I personally think there is essentially no difference, and I prefer to use the second method for plastic conversion.

    reply
    0
  • Cancelreply