1.typeof
typeof 'hello'; // 返回 "string"
typeof 123; // 返回 "number"
typeof true; // 返回 "boolean"
typeof undefined; // 返回 "undefined"
typeof function(){}; // 返回 "function"
typeof null; // 返回 "object"
typeof [1,2,3] // 返回 "object"
优点:检测基本数据类型,简单、快速,适用于大多数情况下
缺点:其中数组、对象、null 都会被判断为 object
2.Object.prototype.toString.call()
console.log(Object.prototype.toString.call('hello')); // 返回 "[object String]"
console.log(Object.prototype.toString.call(123)); // 返回 "[object Number]"
console.log(Object.prototype.toString.call(true)) ; // 返回 "[object Boolean]"
console.log(Object.prototype.toString.call(undefined)); // 返回 "[object Undefined]"
console.log(Object.prototype.toString.call(function(){})); // 返回 "[object Function]"
console.log(Object.prototype.toString.call(null)); // 返回 "[object Null]"
console.log(Object.prototype.toString.call([123,4324])); //[object Array]
优点:可以检测所有类型、判断复杂的数据类型,包括数组、正则表达式等。
缺点:需要调用 Object.prototype.toString.call() 方法,语法较复杂
instanceof
console.log(2 intanceof Number) // false
console.log( [] intanceof Array ) // true
instanceof 运算符用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上,顺着原型链去找,直到找到相同的原型对象,返回true,否则为false,这个东西本身的出现不是为了判断数据类型
优点:可以区分复杂的数据类型如数组和正则表达式。
缺点:无法判断基本数据类型,无法判断 null 和 undefined 类型。