引言
在开发的过程中,经常会涉及到类型的转换,比如数字类型与字符串类型互相转换等,在JS中拥有很多内置方法实现数据类型的转换,不需要自己额外去编写,直接调用即可。
其它类型转成字符串类型
toString()
例:
//数字类型转字符串
var num = 111;
console.log(num);
console.log("the type of num:"+typeof num);
var str =num.toString();
console.log(str);
console.log("the type of str:"+typeof str);
//布尔类型转字符串
var bool = true;
console.log(bool);
console.log("the type of bool:"+typeof bool);
var str2 =bool.toString();
console.log(str2);
console.log("the type of bool:"+typeof bool);
注意:
- null和undefined没有toString()方法
- toString()不会影响到原变量,会将转换的结果返回
其它类型转为数字类型
Number()
例:
//字符串转数字
var str1 ='123';
console.log(str1);
console.log("the type of str1 :"+typeof str1);
var num1 =Number(str1);
console.log(num1);
console.log("the type of num1 :"+typeof num1);
注意:
- 字符串中有非数字内容,则转为NaN
- 空字符串或者全是空格的字符串会转化为0
- undefined转数字类型为NaN
- null转数字类型为0
- 布尔类型True转数字类型为1
- 布尔类型False转数字类型为0
parseInt()与parseFloat()函数
上述的Number()函数无论混合字符串是否存在有效整数都会返回NaN,因此为了提取字符串中的有效整数,JS中可以利用
parseInt()提取有效整数
parseFloat()提取有效小数
例:
var str1 ='123.321abc';
//提取整数
var num1 =parseInt(str1);
console.log(num1);
//提取小数
var num2 =parseFloat(str1);
console.log(num2);
注意:提取过程中如果遇到字符串中有非数字则会停止继续提取。
以上仅作为本人学习JS的笔记记录,如果有地方表达不正确,欢迎各位大神指点迷津。