typeof
作用:用于判断一个一个表达式,(对象或者原始值),返回一个字符串。
用法 typeof a
类型 结果
Undefined : “undefined”
Null : “object” (历史遗留问题)
Boolean: “boolean”
Number : “number”
String : “string”
Symbol (ECMAScript 6 新增): “symbol”
函数对象 : “function”
任何其他对象 : “object”
例子:
console.log(typeof 1); // number
console.log(typeof test); // function
console.log(typeof "yunxi"); // string
console.log(typeof undefined); // undefined
console.log(typeof []); // object
console.log(typeof /\d+/g); // object
instanceof
作用:instanceof 运算符用来测试一个对象在其原型链中是否存在一个构造函数的 prototype 属性。
用法:object **instanceof** constructor
前面是个对象,后面是一个构造函数。而且返回的是布尔型的,不是true就是false。
常见例子:
判断是否为数组[] instanceof Array //true
typeof 与instanceof结合判断数据类型
我们希望有个方法能将js中所有内置对象进行判断
Object Boolean String Number Function Array RegExp Date Error Null,Undefined
function getObjType(obj) {
if(obj === null){
return "null";
}else if(typeof obj === "object"){
if(obj instanceof Array){
return "array";
} else if(obj instanceof RegExp){
return "regExp";
}else if(obj instanceof Date){
return "date";
}else if(obj instanceof Error){
return "error";
} else{
return "object";
}
}else{
return typeof obj;
}
}
测试结果: