JS基本数据类型之间的转换
基本数据类型
1. number
2. string
3. boolean
4. undefined
5. null
一.转换为string
1.调用toString()方法
因为null和undefined没有toString()方法,所以,不能通过这样的方式进行转换。
var a = 123;
var b = a.toString();
console.log(typeof b + " " + b);
a = true;
b = a.toString();
console.log(typeof b + " " + b);
2.通过String()函数
var a;
var b = String(a);
console.log(typeof b + " " + b);
a = null;
b = String(a);
console.log(typeof b + " " + b);
a = 123;
b = String(a);
console.log(typeof b + " " + b);
a = true;
b = a.toString();
console.log(typeof b + " " + b);
3. + "" (加一个空串"")
这种方式的本质,还是调用了String()函数
var a;
var b = a + "";
console.log(typeof b + " " + b);
a = null;
b = a + "";
console.log(typeof b + " " + b);
a = 123;
b = a + "";
console.log(typeof b + " " + b);
a = true;
b = a + "";
console.log(typeof b + " " + b);
二.转换为number
1.使用Number()函数
//字符串转数字
//纯数字字符串,直接转
var a = "123";
var b = Number(a);
console.log(typeof b + " " + b);
//含有非数字字符,转换为NaN
a = "123x";
b = Number(a);
console.log(typeof b + " " + b);
//布尔值转数字 true转为1,false转为0
var a = true;
var b = Number(a);
console.log(typeof b + " " + b);
a = false;
b = Number(a);
console.log(typeof b + " " + b);
//null转为0
var a = null;
var b = Number(a);
console.log(typeof b + " " + b);
//undefined转换为NaN
var a;
var b = Number(a);
console.log(typeof b + " " + b);
2.使用parseInt()或parseFloat()函数
和Number()的不同
1. 对于非字符串类型,先转换为字符串
2. 从左向右遍历字符串,直到碰到非数字字符进行“截断”;如果第一个字符就是非数字字符,转换为NaN
var a = true;
var b = parseInt(a);
//首先,将boolean型的true转换为字符串"true"
//因为没有数字字符,所以为NaN
console.log(typeof b + " " + b);
a = "123";
b = parseInt(a);
console.log(typeof b + " " + b);
a = "A123";
b = parseInt(a);
console.log(typeof b + " " + b);
3.通过一元运算符 + (正号)
本质上调用了Number()函数
var a;
var b = +a;
console.log(typeof b + " " + b);
a = null;
b = +a;
console.log(typeof b + " " + b);
a = true;
b = +a;
console.log(typeof b + " " + b);
a = "123";
b = +a;
console.log(typeof b + " " + b);
a = "123A";
b = +a;
console.log(typeof b + " " + b);
三.转换为Boolean
1.通过Boolean()函数
Boolean(Number) 0和NaN转换为false,其他均为true
Boolean(String) ""(空串)为false,其他均为true
Boolan(null),Boolean(undefined)均为false
2.!!两次取反
本质上调用了Boolean()函数