什么是类型转换?
自动(隐式类型转换)或强制(显示类型转换)改变变量类型的操作/运算【个人理解,仅供参考】
继续之前,你应该知道基本数据类型(也叫基本数据类型的包装类型):Number,String,Boolean
还有两个特殊的Null,Undefined。
类型转换分类:
- 隐式类型转换
- 显示类型转换
隐式类型转换:
Number:
String(字符串)---->Number:
//使用方式: //得到一个数值 //1. 字符串(其中的字符必须为Number类型)通过 -、*、/、%与数值型(Number类型)进行算术运算 //2. 字符串(其中的字符必须为Number类型)通过 -、*、/、%与字符串型(字符为Number类型)进行算术运算 //得到NaN(Not a Number: 不是一个数字的数值类型的值) //3. 字符串(其中的字符不全为Number类型)通过 -、*、/、%与数值型(Number类型)进行算术运算
var num = "123" / 1; //结果为:"num=123, typeof=number" , 方式1的测试num = "123" / "123"; //"num=123, typeof=number" , 方式2的测试num = "123a" / 1; //"num=NaN, typeof=number" , 方式3的测试console.log("num=" + num + ", typeof=" + typeof num);
Boolean(布尔值)---->Number:
//使用方式: //得到一个数值 //1. true----> 1 //2. false----> 0
var num = false * 1; //结果为:"num=0, typeof=number", 方式1的测试num = true + 1; //结果为:"num=2, typeof=number", 方式2的测试console.log("num=" + num + ", typeof=" + typeof num);
Null(空值)---->Number:
//使用方式: //得到一个数值 //1. null---->0
var num = null * 1;//结果为:"num=0, typeof=number"console.log("num=" + num + ", typeof=" + typeof num);
Undefined(未定义)---->Number:
//使用方式: //得到一个NaN //1. undefined---->NaN
var num = undefined * 1;//结果为: "num=NaN, typeof=number"console.log("num=" + num + ", typeof=" + typeof num);
String:
基本数据类型---->String:
//使用方式: //通过字符串连接符进行运算时
var str = 1 + "abc";//结果为:"num=1abc, typeof=string"console.log("str=" + str + ", typeof=" + typeof str);
引用类型数据---->String:
//使用方式: //对引用类型数据进行输出时(console.log(),document.write(), alert()),默认会调用toString()方法,返回一个字符串
var arr = [1, 2, 3];//alert(arr);//document.write("arr=" + arr);console.log(arr);
Boolean:
//为了方便,这里定义一个函数:(解释一下,就是看看你传入的值是不是会自动进行转换为布尔值(true/false), //因为if条件语句中表达式结果只能为true/false) function fnIsBool(iValue) {//iValue会不会自动转换为布尔型的值? if(iValue) {//true console.log("bool=" + true + ", typeof=" + typeof iValue); } else {//false console.log("bool=" + false + ", typeof=" + typeof iValue); } }
Number---->Boolean:
fnIsBool(0);//输出为:falsefnIsBool(0.0);//输出为:falsefnIsBool(NaN);//输出为:false
Stirng---->Boolean:
fnIsBool("");//空字符串 //输出为:false
Null---->Boolean:
fnIsBool(null);//输出为:false
Undefined---->Boolean:
fnIsBool(undefined);//输出为:false
总结一句话:除了以上6中情况为false外,其他的都会隐式转换为true