Javascript - typeof & instanceof 操作符
1. typeof: 返回的是对象类型的字符串,可以返回的字符串有"string", "number", "boolean", "undefined", "object", "function". Javascript 自定义的内置对象,都是返回"function", 包括Object!
typeof 5 ; //return“number”
typeof "a" ; //return "string"
typeof true ; //return "boolean"
typeof undefined ; //return " undefined"
typeof Number; typeof Boolean; typeof Date; typeof String; typeof Object; typeof Aarry; //return "function"
var c = {}; typeof c; //return "object"typeof null; //return "object"
typeof window; //return "object"
typeof(typeof 5); //return "string"
提示: if(typeof a != "undefined") 比 if(a) 好,因为如果a没有定义,if(a) 会报错,因为javascript不需要用没有定义的变量!
2. instanceof : 返回一个Boolean值,指出对象是否是特定对象的一个实例
window instanceof Object; //return true
[] instanceof Array; //return true
var a ={} ; a instanceof Object;//return true
Number instanceof Object; String instanceof Object; Array instanceof Object; Date instanceof Object; Error instanceof Object; Object instanceof Object; //return true
null instance of Object; //return false
undefined instance of Object; //return false
提示:我们大家也许都认为arguments是一个Array,但如果使用instaceof去测试会发现arguments不是一个Array对象,尽管看起来很像
function test(){alert(arguments instanceof Array);}; test(1,2); //It will show false , as arguments is not an array!
1) 对于Array,Number,String,Date,Error,Boolean,Object等特殊对象使用typeof 一律返回"function",这正是typeof的局限性
2) Number/String/Boolen/Object/Date/Error instanceof Object 都返回 true
3) typeof 能返回“object” 结果的有
var c = {}; typeof c; //return "object"
typeof null; //return "object"
typeof window; //return "object"
4)instanceof 中的特殊例子,因为null和undefined不是Object
null instance of Object; //return false
undefined instance of Object; //return false
5)以下代码可以说吗typeof 和instanceof 的不同用处
var colors = ["red", "green", "blue"];
colors[0]= new String("1")
console.log(typeof colors[0]); //output "object"
console.log(colors[0] instanceof String); //output "true";