比较typeof与instanceof 两者常用来判断一个变量是否为空或者是什么类型的 typeof 1)一般只能返回number、boolean、string、function、object、undefined 2)用typeof来获取变量是否存在, if(typeof a != "undefined") 不能直接用if(a),因为如果a不存在(未声明)会报错 3)对于Array\Null特殊对象使用typeof一律返回object 4)Array.isArray()方法判断值是不是数组 5)判断一个值是否为空用value === null
instanceof 1)用来判断a是否为b是实例,如果是就返回true。instanceof检测是原型 2)只能判断出一个变量是否属于某个对象的实例,不能判断变量的实例具体属于那种类型 3)Array也会返回object 4)function test() {} var a = new test() alert(a instance of test )// true
5)console.log(Object instanceof Object);//true console.log(Function instanceof Function);//true console.log(Number instanceof Number);//false console.log(String instanceof String);//false
console.log(Function instanceof Object);//true