JavaScript 四种数据类型检测方法,你掌握了没?

53 阅读1分钟

检测关键字: typeofinstanceofObject.prototype.toStringconstructor

typeof

  • 对于基本数据类型来说,除了 null (检测null会返回object)都可以显示正确的类型
  • 对于引用数据类型来说,除了函数都会显示 object
  • 不存在的变量、函数或者 undefined,将返回 undefined

instanceof

语法:对象 instanceof 构造函数 (返回的是布尔值)

原理:内部机制是通过原型链来判断的

作用:用于判断一个对象是否属于另外一个构造函数

const Person = function() {} 
const p1 = new Person() 
p1 instanceof Person // true 

var str = 'hello world' 
str instanceof String // false 

var str1 = new String('hello world') 
str1 instanceof String // true

📌注意 instanceof 的结果并不一定是可靠的,因为在 ES7 规范中可以通过自定义 Symbol.hasInstance方法来覆盖默认行为。


Object.prototype.toString

JavaScript 中 , 通 过Object.prototype.toString 方法,判断某个对象值属于哪种内置类型。 toString()方法和Object.prototype.toString.call()方法对比

var arr=[1,2];
//直接对一个数组调用 toString()
arr.toString();// "1,2"
//通过 call 指定 arr 数组为 Object.prototype 对象中的 toString 方法的上下文
Object.prototype.toString.call(arr); //"[object Array]"

constructor

来判断数据的类型,但是除了null、undefined,因为他们不是由对象构建

var num = 1;
num.constructor//ƒ Number() { [native code] }
//---------------------------------------------------
true.constructor//ƒ Boolean() { [native code] }
//---------------------------------------------------
"".constructor//ƒ String() { [native code] }
//---------------------------------------------------
var func = function(){}
func.constructor//ƒ Function() { [native code] }
//---------------------------------------------------
[].constructor//ƒ Array() { [native code] }
//---------------------------------------------------
var obj = {}
obj.constructor//ƒ Object() { [native code] }