Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Number 和 parseInt 转化数值有何不同? #33

Open
fwon opened this issue Mar 1, 2017 · 0 comments
Open

Number 和 parseInt 转化数值有何不同? #33

fwon opened this issue Mar 1, 2017 · 0 comments

Comments

@fwon
Copy link
Owner

fwon commented Mar 1, 2017

parseInt 为解析函数,传递的参数需为字符串,非字符串参数会首先被强制类型转换为字符串。解析按照从左到右的顺序,如果遇到非数字字符就停止。

Number为转换函数,不允许出现非数字字符,否则会失败并返回NaN,具体的转化规则请参考其他问题中的分析。

var a = "42";
var b = "42px";

Number(a); //42
parseInt(b); //42

Number(b); //NaN
parseInt(b); //42

关于parseInt一些看似诡异的问题,只要明白参数会被转化为字符串再进行解析,就不会觉得奇怪了,试试看能不能理解下面这些运算的返回值。

parseInt(0.000008);  //0
parseInt(0.0000008); //8
parseInt(false, 16); //250
parseInt(parseInt, 16); //15
parseInt("0x10"); //16
parseInt("103", 2); //2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant