1、typeof
typeof 返回一个表示数据类型的字符串,返回结果包括:number、boolean、string、object、undefined、function、symbol等7种数据类型。
举个栗子:
typeof null; // object
typeof undefined; // undefined
typeof 1; // number
typeof '1'; // string
typeof []; // object
typeof true; // boolean
typeof function() {}; // function
typeof Symbol(); // symbol
有栗子可见,typeof对于基本类型的判断相对比较准确(null除外),对于引用类型的无能为力。下面介绍一种能判断引用类型的方法。
2、instanceof
instanceof 是用来判断 A 是否为 B 的实例对,表达式为:A instanceof B,如果A是B的实例,则返回true,否则返回false。
举个栗子
[] instanceof Array; // true
function() {} instanceof Function; // true
{} instanceof Object; // true
虽然instanceof可以判断引用类型,但是对于基本类型又无能为力了,有没有一种方式既能判断基本类型又能判断引用类型呢,请看第三种方法。
3、Object.prototype.toString .call()
举个栗子
Object.prototype.toString.call(null); // [object Null]
Object.prototype.toString.call(undefined); // [object Undefined]
Object.prototype.toString.call(1); // [object Number]
Object.prototype.toString.call('1'); // [object String]
Object.prototype.toString.call([]); // [object Array]
Object.prototype.toString.call(true); // [object Boolean]
Object.prototype.toString.call(function(){}); // [object Function]
Object.prototype.toString.call({}); // [object Object]
到这里,我们已经可以对数据类型有了准确的判断,至于这些方法的原理是什么,请看后面的文章003-instanceof原理。