转载文章:JS中8种数据类型、4种类型检测方法总结 - 掘金
八种类型
数据类型的四种判断方法
1、typeof
可以用于检测基本类型(除了null
),
但碰到引用类型除了函数返回function, 其他均返回为object
,无法精准判定。
2、instanceof
可以用于引用类型的检测,但对于基本类型是不生效的;
另外,不能用于检测null
和undefined
, 会抛错。
3、撇去null、undefined
,constructor
能用于检测js
的基本类型和引用类型,但当对象的原型更改之后,constructor
便失效了。如下:
function fun() {};
fun.prototype = new Array();
let f = new fun();
console.log(f.constructor===fun); // false
console.log(f.constructor===Array); // true
4、Object.prototype.toString.call()
可用于检测js
所有的数据类型,完美~
总结:
说明:上图中constructor也能检测Symbol和BigInt