javaScript数据类型转换
Posted by xiongmao; tagged with javaScript数据类型转换 , js数据类型转换
1.数字型转换字符串型 :
① 变量.toString();
var num = 10;
var str = num.toString();
console.log(str);
console.log(typeof str);
②. 强制类型转换
String(变量);
console.log(String(num));
③.隐形转换,利用 + 拼接字符串方法实现
console.log(num + '');
var num1 = 11;
console.log(num1);
2.转换为数字型
①. 转换为整形 parseInt(变量);
console.log(parseInt('3.14'));//3
console.log(parseInt('3.94'));//3
console.log(parseInt('120px'));//120
console.log(parseInt('rem120px'));//NaN
②. 转换为浮点型parseFloat(变量)
console.log(parseFloat('3.14'));//3.14
console.log(parseFloat('120px'));//120
console.log(parseFloat('rem120px'));//NaN
③ 强制类型转换 Number(变量)
var str = '123';
console.log(Number(str));
console.log(Number('12'));
④. 4.利用了运算符 - * / 隐式转换
console.log('12' - 1);//11
console.log('123' - '123');
- 转换为布尔型Boolean()
转化为布尔型 Boolean() 函数
代表空,否定的值都会转换为false , 如:",0,NaN,undefined
其余值都会被转换为true
//以下全是flase
console.log(Boolean(''));
console.log(Boolean(0));
console.log(Boolean(NaN));
console.log(Boolean(undefined));
console.log(Boolean(null));
//以下转换全是true
console.log(Boolean(12));
console.log(Boolean('小白'));