typeof 用来检测数据类型的运算符(返回一个字符串,适合函数对象和基本类型的判断) 检测的不管是数组还是正则都返回的是"object",所以typeof不能判断一个值是否为数组
var a = 123; var b = '123'; var c = false; var d = null; var e = undefined; var f = {}; var g = function(){}; var h = []; var i = NaN; console.log(typeof a);//number console.log(typeof b);//string console.log(typeof c);//boolean console.log(typeof d);//object console.log(typeof e);//undefined console.log(typeof f);//object console.log(typeof g);function console.log(typeof h);//object console.log(typeof i);//number 注:console.log(typeof typeof typeof [12, 23]);//string 两个或多个typeof一起使用时,返回string
返回一个布尔值,判断对象类型(基于原型链的方式) 我们使用instanceof/constructor可以检测数组和正则了 原理: 左边对象的原型链(_proto_原型)上是否有右边构造函数的prototype对象属性 不适用于基本数据类型。
var a = 123; var b = '123'; var c = false; var d = null; var e = undefined; var f = {}; var g = function(){}; var h = []; var i = NaN; console.log(a instanceof Number);//false console.log(b instanceof String);//false console.log(c instanceof Boolean);//false console.log(d instanceof Object);//false console.log(e instanceof Object);//false console.log(f instanceof Object);//true console.log(g instanceof Function);true console.log(h instanceof Array);//true console.log(i instanceof Number);//false NaN是基本数据类型
注意:alert(typeof(null)); //object alert(null instanceof Object); //false
在Object基本类定义的这个toString()方法,是用来检测数据类型的; Object.prototype.toString是用来返回对应值的所属类信息的 跟字符串、数字、布尔等原型上定义的toString()方法基本用法都是转换字符串的。
console.log(Object.prototype.toString.call(1));//[object Number] console.log(Object.prototype.toString.call(''));//[object String] console.log(Object.prototype.toString.call(true));//[object Boolean] console.log(Object.prototype.toString.call(null));// [object Null] console.log(Object.prototype.toString.call(undefined));//[object Undefined] console.log(Object.prototype.toString.call([]));// [object Array] console.log(Object.prototype.toString.call({}));// [object Object] console.log(Object.prototype.toString.call(/^$/));//[object RegExp] console.log(Object.prototype.toString.call((function () {})));//[object Function] 注意:IE6/7/8 Object.prototype.toString.call(null/undefined)返回的是[object Object]
4.constructor
var a = 123;
var b = '123';
var c = false;
var d = null;
var e = undefined;
var f = {};
var g = function(){};
var h = [];
var i = NaN;
console.log(a.constructor == Number);//true
console.log(b.constructor == String);//true
console.log(c.constructor == Boolean);//true
// console.log(d.constructor == Object);//true
// console.log(e.constructor == Object);//true
console.log(f.constructor == Object);//true
console.log(g.constructor == Function);//true
console.log(h.constructor == Array);//true
console.log(i.constructor == Number);//true