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

那些年你不曾注意过得 - 类型转换 #2

Open
littlewin-wang opened this issue Dec 7, 2017 · 0 comments
Open

那些年你不曾注意过得 - 类型转换 #2

littlewin-wang opened this issue Dec 7, 2017 · 0 comments
Labels

Comments

@littlewin-wang
Copy link
Owner

JavaScript是一门弱类型语言,类型转换可以被显示调用,也可以隐式地被应用在各种逻辑判断和条件判断中。

类型转换从出生开始,就伴随着属于缺陷还是有用设计的争论。作为使用者,我们的角度还达不到语言规范和特性讨论的范畴。

但是任何问题的解决初衷就是要

深入的了解,小心的求证,去其糟粕,取其精华

显式强制类型转换

StringNumber

这两者完成到字符串和到数字的转换

String(..) 遵循 ToString 规则,将值转换为字符串基本类型。Number(..) 遵循 ToNumber 规 则,将值转换为数字基本类型。

+-

  • 将操作数显式强制类型转换为数字
var c = "3.14";
var d = 5+ +c;
d; // 8.14
  • 将日期转换为数字
+ new Date()  // 1512627035812

parseInt

var b = "42px";
Number( b ); // NaN
parseInt( b ); // 42

parseInt 解析允许字符串中含有非数字字符,解析按从左到右的顺序,如果遇到非数字字符就停止。而 Number 转换不允许出现非数字字符, 否则会失败并返回 NaN 。

parseInt( 1/0, 19 );  // 18
parseInt( false, 16 ); // 250
parseInt( parseInt, 16 ); //15

看到这是否有些懵逼,没关系,先给原理

parseInt(..) 先将参数强制类型转换为字符串再进行解析

parseInt(1/0, 19)实际上是parseInt("Infinity", 19)。第一个字符是"I",以19为基数时值为18。第二个
字符 "n" 不是一个有效的数字字符,解析到此为止。

其余两行大家自行分析

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant