1.parseInt(); 转整数
console.log(parseInt(“100”));//100
console.log(parseInt(“100huhu”));//100
console.log(parseInt(“huhu100”));//NAN
console.log(parseInt(“3.1415926535”));//3
console.log(parseInt("-3.1415926535"));//-3
console.log(parseInt("-3.141huhu592"));//-3
2.parseFloat(); 转浮点数
console.log(parseFloat(“100”));//100
console.log(parseFloat(“100huhu”));//100
console.log(parseFloat(“huhu100”));//NAN
console.log(parseFloat(“100.11”));//100.11
console.log(parseFloat("-100.11"));//-100.11
3.Number(); 转为数字
console.log(Number(“10”));//10
console.log(Number(“10huhu”));//NAN
console.log(Number(“huhu10”));//NAN
console.log(Number(“3.14”));//3.14
console.log(Number("-3.14"));//-3.14
console.log(Number(“undefined”));//NaN
console.log(Number(“true”)); //NAN
console.log(Number(“false”));//NAN
console.log(Number(“null”));//NAN
//总结:只要存在字母或者特殊字符,都会转化成NaN
//总结: 想要转整数parseInt();
//总结: 想要转小数parseFloat();
//总结: 想要严格的转化为数字Number();
4. .toString(); String();,转字符串类型
var num = true;
console.log(typeof num.toString());//string
var x;//undefined
console.log(typeof String(x));//string
// 总结:变量有意义调用.toString()转换
// 总结:变量没有意义使用String()转换
5.Boolean(值) 转布尔类型
console.log(Boolean(1)); //true
console.log(Boolean(0)); //false
console.log(Boolean(11)); //true
console.log(Boolean(-100)); //true
console.log(Boolean(“huhu”)); //true
console.log(Boolean("")); //false
console.log(Boolean(" “)); //true, " 空格”
console.log(Boolean(null)); //false
console.log(Boolean(undefined));//false
//总结 0 空字符串,null undefined 都是false //字符串 除0以外的数字都是true
JavaScript的类型转换(me笔记)
最新推荐文章于 2024-08-14 09:04:24 发布