Is parseInt() supposed to work like this?

前端 未结 7 1894
不思量自难忘°
不思量自难忘° 2020-12-17 23:15

If I write this script :

alert(parseInt(\"123blahblahblah456\"));

I get the alert with the value 123

Ideally, shouldn\'t th

7条回答
  •  北海茫月
    2020-12-17 23:42

    Yes, cf all the anwers. I'd like to add that this is why checking if certain value can be converted to a number, it's better to use Number or just +.

    Number("123blahblahblah456"); //=> NaN
    Number("123"); //=> 123
    +"97.221" //=> 97.221
    // if the conversion result needs to be an int
    Math.round(Number("123.4567")); //=> 123
    

    Be aware though that Number in some cases (unexpectely) returns 0.

    +null   //=> 0
    +"  "   //=> 0
    +""     //=> 0
    +false  //=> 0
    +[]     //=> 0
    

提交回复
热议问题