强制数据类型转换
其它数据类型转为数字
- Number(数据);可以转换字符串 布尔 null,字符串必须是纯数字字符,可以识别小数点(只能识别一个)true是1 false是0 null ->0 转不成数字返回NaN
Number转化
console.log(Number(100));
var str = "123";
console.log(typeof str);//123
console.log(typeof Number(str));//number
console.log(Number("123.12"));//123
console.log(Number("123.12.123"));//NaN
console.log(Number("456px"));//NaN
console.log(Number("abc123"));//NaN
console.log(Number(true)); //1
console.log(Number(false)); //0
console.log(Number(null)); //0
console.log(Number(undefined)); //NaN
- parseInt(数据); 转为整型,不保留小数只能转换字符串 ,只能识别纯数字字符串,一旦遇到非数字字符就停止转换了,将数字返回,如果开头就是非数字字符返回NaN
// parseInt(数据); 转为整型,不保留小数
// 只能转换字符串
// 只能识别纯数字字符串,一旦遇到非数字字符就停止转换了,将数字返回,如果开头就是非数字字符返回NaN
console.log(parseInt(100));//100
console.log(parseInt("123"));//123
console.log(parseInt("123.123"));//123
console.log(parseInt("123px"));//123
console.log(parseInt("456abc789"))//456;
console.log(parseInt("789.123.123"));//789
console.log(parseInt("abc999")); //NaN
// 以下都是NaN
// console.log(parseInt(true));
// console.log(parseInt(false));
// console.log(parseInt(null));
// console.log(parseInt(undefined));
- parseFloat(数据); 转为浮点型 (保留小数,只能识别一个小数点) 只能转换字符串,只能识别纯数字字符串,一旦遇到非数字字符就停止转换了,将数字返回,如果开头就是非数字字符返回NaN
parseFloat转化
console.log(parseFloat("789.123.123"));//789.123
其它数据类型转为字符串
- String(数据); 类方法
console.log(String("abc")); //"abc"
console.log(String(123));//"123"
console.log(String(true));//"true"
console.log(String(null));//"null"
console.log(typeof String(undefined));//"undefined"
- 变量.toString(); 私有方法,有这个方法才能使用,没有就不能使用 可以转为对应的进制字符串 参数范围 2-36 默认是10进制
var a = 123;
var b = true;
var c = "hello";
var d = null;
var f = undefined;
console.log(a.toString());
console.log(b.toString());
console.log(c.toString());
// console.log(d.toString()); //ncaught TypeError: Cannot read property 'toString' of null
// console.log(f.toString()); //TypeError: Cannot read property 'toString' of undefined
// 转为进制字符串
var num1 = 10;
console.log(num1.toString());
console.log(num1.toString(2)); //先转为2进制 再变为字符串 "1010"
/*
这两个方法的区别:
String(数据); 类方法 可以将任意数据类型转为字符串
变量.toString(); 私有方法,有才可以使用比如null和undefined没有这个方法,就不能使用,可以转为进制字符串
*/
其它数据类型转为布尔
- Boolean(数据); 可以将任意数据类型转为布尔
- 规律:对于单个数据而言只有0 NaN null undefined “” 是假的,其它的都是真的
隐式数据类型转换
// 1.+一旦遇到字符串就表示拼接
console.log("10"+20); //"1020"
// 不同数据类型进行运算的时候,会尽量转为数字(隐式转换,内置帮我们转的)并且符合Number的规律
//2. - * / %
console.log(10 - "2");// 8
console.log(10 - "2px");// 10 - NaN => NaN
// 3.toFixed(n); 保留几位小数,转为对应的字符串
var a = 10;
var b = 10.235678;
console.log(a.toFixed(2));
console.log(b.toFixed(2));
//4.isNaN(数据); 判断当前数据是否是数字,是数字返回false,不是数字返回true
// 内存存在隐式转换,先将数据转为数字 符合Number的规律
console.log(isNaN(10));//false
console.log(isNaN("100")); //false
console.log(isNaN("100px"));//true