你不知道Js数据类型能有多复杂(一)
大一暑假:2022-8-11
4种检测数据类型的方法:
typeof
检测数据类型的逻辑运算符instanceof
检测是否为某个类的实例constructor
检测构造函数Object.prototype.toString.call
检测数据类型
typeof
语法:typeof value
或 typeof (value)
,但是第一种语法更为常见。
作用:返回当前value
的数据类型。
typeof 12 //"number"
typeof true //"boolean"
typeof "string" //"string"
typeof null //"object"
typeof undefined //"undefined"
typeof Symbol('1') //"symbol"
typeof BigInt('1') //"bigint"
typeof {} //"object"
typeof [] //"object"
typeof function(){} //function
特点:
- 返回的结果都是字符串
2个特殊返回结果:
typeof null
=> “object” 而不是"null"typeof function
=> “function” 而不是"object"
局限性
typeof
不能细分对象类型(检测数组对象、日期对象等返回结果都是"object",而检测function对象却例外)
经典面试题一
let a = typeof typeof typeof [12,23];
console.log(a)
标准答案:输出"string"
分析:从右到左运算
第一步:typeof [12,32]
=>"object"
第二步:typeof "object"
=>"string"
第三步:typeof "string"
=>"string"
经典面试题二
let res = parseFloat("left:200px") //NaN
if(res===200){
console.log(200)
}else if(res === NaN){ //NaN != NaN
console.log(NaN)
}else if(typeof res === 'number'){ //NaN属于number类型
console.log('number')
}else{
console.log('Invalid Number')
}
控制台打印什么?
答案:number
经典面试题三
console.log(parseInt("")) //NaN
console.log(Number("")) //0
console.log(isNaN("")) //false
console.log(parseInt(null)) //NaN
console.log(Number(null)) //0
console.log(isNaN(null)) //false
console.log(parseInt("12px")) //12
console.log(Number("12px")) //NaN
console.log(isNaN("12px")) //true
console.log(parseFloat("1.6px")+parseInt("1.2px")+typeof parseInt(null)) //1.6+1+'number'=>2.6+'number'=>'2.6number'
console.log(isNaN(!!Number(parseInt("0.8")))) //!!0=>true false
console.log(typeof !parseInt(null) + !isNaN(null))//!NaN=>'true' =>'boolean'+true=>'booleantrue'
注意:
0 、
NaN
、null
、undefined
、''
转化为布尔值都是false
[]==true =>false 都转换为数字
Number([])
=>Number('')
=>0,true=>1
==
双等号比较规律:
- 1.对象和字符串比较是时 => 对象转化为字符串
- null和undefined 或null比较时时为true,剩下null和任何值比较都为false
- 剩下两边不同比较时都转化为数字
恐怖如斯的腾讯面试题
console.log(10+false+undefined+[]+'Tencent'+null+true+{})
- 第一步:10+
false
=>10+0=>10 - 第二步:10+
undefined
=> 10+NaN
=>NaN
- 第三步:
NaN
+[]
=>NaN
+''
=>'NaN'
- 第四步:
'NaN'
+'Tencent'
=>'NaNTencent'
- 第五步:
'NaNTencent'
+null
=>'NaNTencentnull'
- 第六步:
'NaNTencentnull'
+true
=>'NaNTencentnulltrue'
- 第七步
'NaNTencentnulltrue'
+{}
=>'NaNTencentnulltrue[object object]'
所以,最后控制台输出NaNTencentnulltrue[object object]
本文含有隐藏内容,请 开通VIP 后查看