基本数据类型(值类型/原始值类型)
+ number
+ string
+ boolean
+ null
+ undefined
+ symbol
+ bigInt
引用数据类型
+ object
+普通对象 Map
+实例对象
+数组对象 Set
+正则对象
+日期对象
+prototype原型对象
...
+ function
//数字类型中比较奇怪的值
+ NaN 不是有效数字,但是属于number类型 //typeof NaN
+ NaN==NaN //false
//检测有效数字 isNaN
Object.is(NaN,NaN) //true
console.log(Infinity)
//数据类型检测
+ typeof //结果为字符串 typeof null->'object' 不属于对象,因为二进制存储以000开头了,对于对象结果都是'object'
+ instanceof
+ constructor
+ Object.prototype.toString.call([value])
<1>其他类型转换为Number类型
1.手动转Number
+ Number()
console.log(Number('')) //0
console.log(Number('10')) //10
console.log(Number('10px')) //NaN 出现非有效数字就是NaN
console.log(Number(true)) //1
console.log(Number(false)) //0
console.log(Number(null)) //0
console.log(Number(undefined)) //NaN
console.log(Number(Symbol(10))) //报错
console.log(Number(BigInt(10)) //10
//对象变数字,先valueof,没有用toString,再转数字
+ parseInt
//先转字符串,从字符串第一个字符开始查找有效数字,遇到非有效数字停止查找,再转数字
//如果开始就没有有效数字 为NaN
+ parseFloat 比 parseInt 多识别小数点
parseInt('') //NaN
Number('') //0
isNaN('') //先Number('')转数字0 结果false
parseInt(null) //NaN
Number(null) //0
isNaN(null) //false
parseInt("12px") //12
Number("12px") //NaN
isNaN("12px") //true
parseFloat('1.6px')+parseInt("1.2px")+typeof parseInt(null) //1.6+1+'number' ->'2.6number'
//对象遇到+ 先转字符串
isNaN(Number(!!Number(parseInt('0.8'))))
//parseInt('0.8')->0
//!!0->false
//isNaN(0)->false
typeof !parseInt(null)+!isNaN(null)
//parseInt(null)->NaN
//!NaN ->true
//typeof true ->'boolean'
//!isNaN(null) true
//'booleantrue'
2.隐式转换(默认的)
+ isNaN()
+ 数学运算(注意:加号遇见字符串不是数学计算,是字符串拼接)
+ 在==比较的时候,有些值需要转换为数字再进行比较
...
<2>其他类型转换为字符串
1. 手动
+ toString()
+ String()
2. 隐式转换(一般调用toString)
+ 加号运算,如果一边出现字符串,就是字符串拼接
+ 把对象转换为数字,先toString()转换为字符串,再去转换为数字
+ 基于alert/confirm/prompt/document.write...这些都是转字符串输出
...
规则:普通对象转字符串调Object.prototype.toString,结果是'[object object]',其他一般都是值包起来
<3>其他类型转换为布尔
1.手动
+ ! 转换为布尔值后取反
+ !! 转换为布尔类型
+ Boolean()
2.隐式
+ 在循环或者判断条件中,条件处理的结果就是布尔值
...
规则:只有 '0、NaN、null、undefined、空字符串' 五个值会变为布尔的FALSE,其余都是TRUE
<4>在==比较的过程中,数据转换的规则:
1.类型一样的特殊点
{}=={}:false 对象比较堆内存地址
[]==[] false
NaN==NaN false
2.类型不一样的转换规则
1. null==undefined true,但是换成===是false(类型不一样),剩下null/undefined和其他任何数据类型值都不相等
2. 字符串==对象 要把对象转换成字符串
3. 剩下如果==两边数据类型不一致,都需要转换成数字再进行比较
测试题:
console.log([]==false) true
//转成数字判断 左边对象toString再转数字(如果有valueof原始值为基本类型则先valueof)
//[]->''-> false->0
console.log(![]==false) true
//![]->!(true)->false ([]不是'0、NaN、null、undefined、空字符串' 五个值中的一个所以为true)
let result = 10+false+undefined+[]+'Tencent'+null+true+{}
console.log(result)
//10+0+NaN+''+'Tencent'+'nulltrue'
//'NaNTencentnulltrue[object object]'
let arr =[10.18,0,10,25,23]
arr=arr.map(parseInt)
console.log(arr)
//arr=arr.map((item,idx)=>{})) parseInt 第二个参数为进制 0默认10进制,除了2-36进制不好使为NaN
//parseInt('10.18',0) 10
//parseInt('0',1) NaN
//parseInt('10',2) 2
//parseInt('25',3) 2 只能识别2
//parseInt('23',4) 11
注: 加号 有时候不是字符串拼接
let n='10'
console.log(++n) //11
console.log(+n) //10
{}+0 //左边认为是代码块,不参与运算 ->0
0+{} //这种情况是数学运算 '0[object object]'