js新手入门笔记04-数据类型的转换

223 阅读1分钟

第一种:转换成字符串
1.变量.toString(); 常用
2.String(变量名);
疑惑:为什么会有2种转换方法?
string()函数存在的意义,是因为有些值没有toString(),这个时候可以使用String(),比如undefined和null

第二种:转换成数字
1.Number() ——》 非常严谨的转换方法
字符串 ——》数字:只能转换全部是数字的字符串,有一个其他字符便会返回NaN(not a number);
布尔类型——》数字:true——>1,false——>0;
null——》数字:返回的结果为0;
undefined——》数字:返回的结果为NaN;

2.ParseInt() ——》转换成整数
字符串——》数字
①直接砍掉小数点后面的数字,
②整数如果有不是数字的部分的字符串,将返回NaN
布尔类型、null、undefined ——》数字:直接返回NaN

3.ParseFloat() ——》转换成浮点数
字符串——》数字
①如果是整数,那就直接返回整数
②整数如果有不是数字的部分的字符串,将返回NaN
③在转换小数点后的数时,遇到非数字就会停止转换。 布尔类型、null、undefined ——》数字:直接返回NaN

总结:只有Number()能转换除字符串类型以外的数据,所以看到数据是字符串类型以外的的数据时,想到用Number();

第三种:转换成布尔类型

    	console.log(Booleen(1));  //true

		console.log(Booleen(0));  //false

		console.log(Booleen(22));  //true	

		console.log(Booleen(-5));  //true

		console.log(Booleen("dsd21"));  //true

		console.log(Booleen(""));  //false

		console.log(Booleen("null"));  //false

		console.log(Booleen("undefined"));  //false

总结:1.除了0之外的所有数字转成布尔类型都是true
2.除了空字符串之外的所有字符串转成布尔类型都是true
3.nul和undifined都是false.