使用typeof检测基本数据类型
让我们先来看几个使用 typeof 来判断类型的 实例:
console.log(typeof "1"); // string
console.log(typeof 1); // number
console.log(typeof true); //boolean
console.log(typeof undefined); //undefined
console.log(typeof null);// object
console.log(typeof []); // object
console.log(typeof {}); // object
console.log(typeof window.alert); // function
从上面代码打印的内容来看,基本数据类型(字符串、数值、undefined、布尔)是可以通过typeof来判断的。
以上有一个注意点,在 JavaScript 最初的实现中,JavaScript 中的值是由一个表示类型的标签和实际数据值表示的。对象的类型标签是 0。由于 null 代表的是空指针(大多数平台下值为 0x00),因此,null 的类型标签是 0,typeof null 也因此返回 "object"。typeof null === 'object';
但是在实际工作中,还需要判断时间对象(Date),数学对象(Math)等更加细致的对象,我们可以使用Object.prototype.toString()方法。
使用 toString() 检测对象类型:
每个对象的原型都有一个 toString() 方法,当该对象被表示为一个文本值时,或者一个对象以预期的字符串方式引用时自动调用。默认情况下,toString() 方法被每个 Object 对象继承。如果此方法在自定义对象中未被覆盖,toString() 返回 "[object type]",其中 type 是对象的类型。请看以下代码
var toString = Object.prototype.toString;
console.log(toString.call(new Date)); // [object Date]
console.log(toString.call(new String));// [object String]
console.log(toString.call(Math));// [object Math]
console.log(toString.call(123));//[object Number]
console.log(toString.call(true)); //[object Boolean]
console.log(toString.call(undefined)); // [object Undefined]
console.log(toString.call(null));// [object Null]
可以通过 toString() 来获取每个对象的类型。为了每个对象都能通过 Object.prototype.toString() 来检测,需要以 Function.prototype.call() 或者 Function.prototype.apply() 的形式来调用,传递要检查的对象作为第一个参数,称为 thisArg。