typeof和instanceof结合精准判断类型
作者:
伍超波 | 来源:发表于
2017-10-16 19:16 被阅读0次
一、结合判断的依据是
- 由于typeof只能判断类型,所以,数组和对象返回的都是object,这时就需要使用instanceof来判断了
二、代码如下
function getType(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(getType(111)); //number
console.log(getType("fasd"));//string
console.log(getType(true));//boolean
console.log(getType(function () { }));//function
console.log(getType([]));//array
console.log(getType({}));//object
console.log(getType(null));//null
console.log(getType(undefined));//undefined
console.log(getType(/\n/));//object
console.log(getType());//undefined
本文标题:typeof和instanceof结合精准判断类型
本文链接:https://www.haomeiwen.com/subject/npjluxtx.html
网友评论