1.typeof
形如 :
typeof undefined //undefined
typeof 'qw' //string
typeof 1 //number
typeof true //Boolean
typeof function(){} //function
//不区分null、{}、数组
typeof null //object
typeof {} //object
typeof [] //object
返回类型有: ‘undefined’ “string” ‘number’ ‘boolean’ ‘function’ ‘object’
缺点: 对于object类型不能细分是什么类型 ,比如null、{}、数组
优点: 对undefined的判断 'undefined’的应用
2.instanceof
instanceof用于判断一个变量是否某个对象的实例,最终结果是一个布尔值
形如 :
var d = new String('test');
d instanceof String === true;
null instanceof Object //false
undefined instanceof Object //false
[] instanceof Object //true
[] instanceof Array //true
Function instanceof Object //true
Function instanceof Function //true
var a = 'qwqwq';
a instanceof String //false
"awqwqw" instanceof String //false
返回的类型有: String Number Boolean Function Object Array Date
优点: 可以区分null和undefined不为Object
缺点: 区分不清除 数组,Function,和string,number类型必须是new生成的对象,直接量无法判断。
3.constructor
形如:
var x = [];
x.constructor === Array;
null.constructor === Object //Cannot read property 'constructor' of null
undefined.constructor === undefined //Cannot read property 'constructor' of undefined
优点: 可以返回继承的类型
缺点: 不能对象的细分,如继承 必须手动修正,不能验证null和undefined
4.Object.prototype.toString.call();
Object.prototype.toString.call([]) //"[object Array]"
Object.prototype.toString.call({}) //"[object Object]"
Object.prototype.toString.call(new Date()) //"[object Date]"
Object.prototype.toString.call("") //"[object String]"
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(Function) //"[object Function]"
优点: 通用,返回"[objectString]" 具体object的类型
缺点: 不能返回继承的类型
5.Array.prototype.isPrototypeOf(obj)
Array.prototype.isPrototypeOf([]) //true
Array.prototype.isPrototypeOf({}) //false
Object.prototype.isPrototypeOf([]) //true
Object.prototype.isPrototypeOf({}) //true
优点: 指定判断数组类型
缺点: 不能辨别数组,对象,等引用类型,不辨别,基本类型
6.Array.isArray()
Array.isArray({}) //false
Array.isArray([]) //true
优点: 精准的判断数组
缺点: 只能判断是否是数组