JS类型判断的那些方法

本文详细讲解JavaScript中的类型判断方法,包括typeof的局限性,instanceof对引用类型的识别,以及toString.call的全面性。提供了一个实用的getType函数封装这三种方式。
摘要由CSDN通过智能技术生成

目前类型判断有三种方法:typeof  、instanceof  、Object.prototype.toString.call

typeof:只能判断基础类型和函数类型

typeof 2            // number
typeof true         // boolen
typeof 'str'        // string
typeof function(){} // function
typeof undefined    // undefined

typeof null          // object
typeof {}            // object
typeof []            // object

instanceof:只能判断引用类型

[] instanceof Array                //true
{} instanceof Object               //true
function(){} instanceof Function   //true

666 instanceof Number              //false
'str' instanceof String            //false
true instanceof Blooen             //false

Object.prototype.toString.call:可以判断各种类型,就是结果比较不友好

Object.toString.call(2)             // [object Number]
Object.toString.call('str')         // [object String]
Object.toString.call(true)          // [object Booleen]
Object.toString.call(undefined)     // [object Undefined]
Object.toString.call(null)          // [object Null]

Object.toString.call(function(){})  // [object Funtion]
Object.toString.call({})            // [object Object]
Object.toString.call([])            // [object Array]

根据上面的各种方法,进行封装

1.基本类型和函数类型就直接用typeof直接返回

2.遇到{},[],null的用Object.prototype.toString.call判断后进行截取再转小写

function getType(type) {
    if(typeof type === 'object') {
        retutn Object.prototypeof.toString.call(type).slice(8,-1).toLowerCase()
    } else {
        retutn typeof type
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值