数据类型的转化
在 JavaScript 程序中 , 变量中存储的数据类型没有限制,也就是在变量中可以存储任何符合JavaScript语法规范的数据类型。
数据类型转化的原因:在 JavaScript 程序的执行过程中,往往需要变量中存储的数值是某种特定的数据类型,别的数据类型不行,所以会需要将别的数据类型转化为自己所需的某种特定的数据类型。
数据类型转化:将当前数据类型转化为其他数据类型。
1.自动转化:
1.布尔类型:
条件:使用if else判断语句时
0 、 ‘’ ‘’ 、 undefined 、 null 、 NaN会转化为false
其余的都会转化为true
if(undefined){
console.log( '转化为true' );
}else{
console.log( '转化为false' );
}
if(' '){
console.log( '转化为true' );
}else{
console.log( '转化为false' );
}
2.字符串类型:
条件:字符串拼接
undefined 、 null 、false 、 true都会转化为相应的字符串类型
数值:转化为相应的纯数字字符串
数组:转化时会去掉[ ]就可以了
对象:转化为[ object Object]
函数:转化为字符串
var str4 = '北京' + undefined;
console.log(str4);
var str10 = '北京' + {name:'张三' , age:18 , sex:'男'} ;
console.log(str10);
3.数值类型:
条件:执行数学运算
true为1、false为0、undefined为NaN、null为0
纯数字转化为相应的值(包括科学计数法),有不是数字的则转化为NaN
数组、对象、函数如果时加号则字符串拼接(转化为字符串)、别的一律为NaN
var int3 = 100 - undefined;
console.log(int3);
console.log( 100 + function fun(){console.log(123)} );
2.强制转化:
1.布尔类型:
使用Boolean( 数据/变量 ),别的和自动转化一样,但是不会改变原始数值
var int = 100;
console.log( Boolean(int) );
2.字符串类型:
使用 变量.toString(进制类型)(进制范围在2-36)和String( 变量 / 数据 )
var int = 2e5;
console.log( String(int) );
console.log( int );
3.数值类型:
使用Number(变量/数值) 和自动转化一样
使用parseInt(变量 / 数据) 如果是数值则获取整数部分,如果不是数值则为NaN,需特别注意的时数组。
使用parseFloat( 变量 / 数值 ) 如果是数值,则获取符合浮点数的部分,如果不是数值则获取的是NaN。(科学计数法会被解析)
console.log( parseInt( function fun(){console.log('abc')} ) );
console.log( parseInt( '3.123456e3' ) );
console.log( parseFloat( function fun(){console.log('abc')} ) );
console.log( parseFloat( '3.1223abc' ) );