js中typeof和instanceof介绍

typeof把类型信息当作字符串返回。返回值有:"number","string","boolean","object","function"和"undefined".可以使用typeof获取一个变量是否存在,如if(typeof(str) !="undefined"){},不要去使用if(a),a未声明会出错,对于Array,Null等特殊对象使用typeof一律返回object,这是typeof局限性。

typeof的运算符未定义,返回“undefined”

运算符是数字typeof(str) = "number"

字符串typeof(str) = "string"

布尔值typeof(str) = "boolean"

对象,数组和null typeof(str) = "object"

函数 typeof(str) = "function"

instanceof用于判断一个变量是否属于某个对象的实例

例:

a instanceof b?console.log(true):console.log(false);    //a是b的实例?真:假

1 var a = new Array();
2 console.log(a instanceof Array);    //true
3 console.log(a instanceof Object);   //true
console.log(a instanceof Object)也返回true,因为Array是Object的子类。

注意:

if(window instanceof Object){
    console.log("Y")      
}else{
   console.log("N");  
}

如上,返回“N”,因为instanceof测试的Object是指js语法中的object,不是dom模型对象。

posted @ 2018-03-22 10:52  激战JZ  阅读(255)  评论(0编辑  收藏  举报