有些时候,需要将数据转换为其他类型进行操作,转换方式:强制转换、隐式转换
强制转换
通过方法,将数据必须转换为某种数据类型
强制转换为number
-
Number(要转换的数据) : 强制转换为number类型,不能转换的结果为NaN
-
parseInt(要转换的数据) : 从左往右开始转换,遇到不能转换的或者是末尾就停止,如果一开始就不能转换结果为NaN,取整
-
parseFloat(要转换的数据):从左往右开始转换,遇到不能转换的或者是末尾就停止,如果一开始就不能转换结果为NaN,保留小数
//1.Number(要转换的数据类型):强制转为number类型,会将转换后的结果返回 //字符串转Number---- 纯数字,空字符 var s1 = "10"; var s2 = "10a"; var s3 = ""; console.log(Number(s1)); //"10" ---- 10 console.log(Number(s2)); //NaN console.log(Number(s3)); //0 //boolean转number var b1 = true; var b2 = false; console.log(Number(b1),Number(b2)); //1 0 //null转number var nu = null; console.log(Number(nu)); //0 //undefined转number var u = undefined; console.log(Number(u)); //NaN //2.parseInt(要转换的数据):从左往右开始转换,遇到不能转换的或者是末尾就停止,如果一开始就不能转换结果为NaN,取整 //3.parseFloat(要转换的数据):从左往右开始转换,遇到不能转换的或者是末尾就停止,如果一开始就不能转换结果为NaN var price = "9.9元"; console.log(parseInt(price)); //9 舍弃小数部分 console.log(parseFloat(price)); //9.9 保留小数
强转转换为string
-
String(要转换的内容) : 强制转为string,就是在数据的外层加了引号
//1.String(要转换的内容) : 强制转为string,就是在数据的外层加了引号 var n = 10; console.log(String(n),n); //"10" console.log(String(true)); //"true" console.log(String(false)); //"false" console.log(String(null)); //"null" console.log(String(undefined));//"undefined" console.log(String(NaN));//"NaN"
-
XX.toString()
//2 XX.toString() var n = 10; console.log(n.toString()); var b = true; console.log(b.toString()); //undefined身上没有任何方法,只要是undefiend. 都报错 var u = undefined; //console.log(u.toString()); //Cannot read property 'toString' of undefined // null身上没有任何方法,只要是 null. 都报错 var nu = null; console.log(nu.toString()); //Cannot read property 'toString' of null
-
String和toString的区别?
String是公共方法,toString是对象私有的方法,undefined和没有没有
隐式转换
在运算过程中数据自动进行类型转换
-
isNaN
isNaN : is not a number ,判断数据是否是一个数字,是数字-false,不是数字-true
//1.isNaN : is not a number ,判断数据是否是一个数字,是数字-false,不是数字-true console.log(isNaN(10));//false console.log(isNaN("a"));//true //isNaN在判断之前,会自动调用Number()先将数组转换为number,在判断 console.log(isNaN("10")); //false Number("10") --- > 10 isNaN(10) console.log(isNaN(null)); //false null-->0 console.log(isNaN(true)); //false true--1
-
toFixed()
xx.toFixed(n) : 保留几位小数,四舍五入
//2.xx.toFixed(n) : 保留几位小数,四舍五入 var a = 0.1; var b = 0.2; console.log((a + b).toFixed(1)); //0.3 var n = 3.4567; console.log(n.toFixed(2)); //3.46