typeof
作用:用于判断一个一个表达式,(对象或者原始值),返回一个字符串。
返回的可能的值(摘自mdn)
类型 | 结果 |
---|---|
Undefined | "undefined" |
Null | "object" (历史遗留问题) |
Boolean | "boolean" |
Number | "number" |
String | "string" |
Symbol (ECMAScript 6 新增) | "symbol" |
宿主对象(由JS环境提供) | Implementation-dependent |
函数对象 ( [[Call]] 在ECMA-262条款中实现了) | "function" |
任何其他对象 | "object" |
instanceof
instanceof 运算符用来测试一个对象在其原型链中是否存在一个构造函数的 prototype 属性。
使用规则:
object instanceof constructor
要求前面是个对象,后面是一个构造函数。而且返回的是布尔型的,不是true就是false。
常用使用:
由于typeof只能判断类型,所以,数组和对象返回的都是object,这时就需要使用instanceof来判断是否是
[] instanceof Array //true
function getDataType(obj) {
if(obj === null){
return "null";
}else if(typeof obj === "object"){
if(obj instanceof Array){
return "array";
}else{
return "object";
}
}else{
return typeof obj;
}
}
以下是对每个类型的测试
console.log(getDataType(111)); //number
console.log(getDataType("fasd"));//string
console.log(getDataType(true));//boolean
console.log(getDataType(function () { }));//function
console.log(getDataType([]));//array
console.log(getDataType({}));//object
console.log(getDataType(null));//null
console.log(getDataType(undefined));//undefined
console.log(getDataType(/\n/));//object
var a;
console.log(getDataType(a));//undefined 如果传入没有声明的变量会直接报错