typeof和instanceof 区别以及缺陷,以及解决方案

这两个方法都可以用来判断变量类型

区别:前者是判断这个变量是什么类型,后者是判断这个变量是不是某种类型,返回的是布尔值

(1)typeof  

typeof返回一个数据类型的字符串,而且都是小写的字符串,返回值有'number','boolean','string','function','object','undefined'这几个

typeof 100; //'number'
typeof (1==1); //'boolean'
typeof 'onepixel' ; //'string'
typeof {} ; //'object'
typeof onepixel; // 'undefined'
typeof parseInt; // 'function'
typeof []; //'object'
typeof new Date(); //'object'

缺陷:

1.不能判断变量具体的数据类型比如数组、正则、日期、对象,因为都会返回object,不过可以判断function,如果检测对象是正则表达式的时候,在Safari和Chrome中使用typeof的时候会错误的返回"function",其他的浏览器返回的是object.

2.判断null的时候返回的是一个object,这是js的一个缺陷,判断NaN的时候返回是number

(2)instanceof

可以用来检测这个变量是否为某种类型,返回的是布尔值,并且可以判断这个变量是否为某个函数的实例,它检测的是对象的原型

[] instanceof Array; //true
{} instanceof Object; //true
new Date() instanceof Date; //true
function Person(){};
[] instanceof Object; //true
new Date() instanceof Object; //tru
new Person instanceof Object; //true

var array = new Array()

array instanceof Array //true


共同点:基本数据类型都可以判断

不同点:instanceof可以判断这个变量是否为某个函数的实例,而typeof不能

用法:typeof经常用来检测一个变量是不是最基本的数据类型,instanceof简单说就是判断一个引用类型的变量具体是不是某种类型的对象。

联系:typeof和instanceof的目的都是检测变量的类型,两个区别在于typeof只能用于检测基本数据类型,instanceof可以检测基本数据类型,也可以检测某些引用数据类型,因为instanceof只能通过true或者false来判断,不能直接看出来是什么类型,所以需要另外一种直观的方法:

解决方案

因为js中的一切都是对象,任何都不例外,对所有值类型应用 Object.prototype.toString.call() 方法结果如下:

console.log(Object.prototype.toString.call(123)) //[object Number]
console.log(Object.prototype.toString.call('123')) //[object String]
console.log(Object.prototype.toString.call(undefined)) //[object Undefined]
console.log(Object.prototype.toString.call(true)) //[object Boolean]
console.log(Object.prototype.toString.call({})) //[object Object]
console.log(Object.prototype.toString.call([])) //[object Array]
console.log(Object.prototype.toString.call(function(){})) //[object Function]

判断是否为函数

function isFunction(it) {
return Object.prototype.toString.call(it) === '[object Function]';
}

判断是否为数组:

function isArray(o) {
return Object.prototype.toString.call(o) === '[object Array]';
}

利用这个特性,可以写一个比typeof instanceof更准确的判断方法:

var type = function (o) {

    var s = Object.propertype.toString.call(o)

   return s.match(/\[object(.*?)\]/)[1].toLowerCase()

}

type({}); // "object"
type([]); // "array"
type(5); // "number"
type(null); // "null"
type(); // "undefined"
type(/abcd/); // "regex"
type(new Date()); // "date"复制代码

其他方法总结:

数组:

var a = [1, 2, 3]

var b = {}

Array.isArray(a)  //  true

Array.isArray(b)  // false



转载于:https://juejin.im/post/5a485d96f265da432e5c5931

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值