数据类型及检测

基本数据类型

值类型

numberstringnullundefinedboolean

引用类型

object:({ },[ ],Math、Data、/^$/、实例对象)、function

检测数据类型

(以下将介绍四种检测方法)

  • typeof
  • instanceof
  • constructor
  • Object.prototype.toString.call([value])

方法一

  • typeof() 基于计算机底层数据类型的值(二进制)进行检测 。例如:对象以000开头…
  • 常用于基本数据类型的检测
  • 缺点:Object类型不能进行具体检测
typeof();  //返回字符串
typeof(12); //"number"
typeof([1,2]);//"object"
typeof {} ; //"object"
typeof null //"object"  !!!重点
typeof NaN    //"number"
typeof undefined // "undefined"

方法二(右边必须为Object类型)

  • instanceof用于检测具体的Object类型,不能检测基本类型!!!
//instanceof
[] instanceof Array  //true
function(){} instanceof Function   //true
{} instanceof Object   //true

1 instanceof Number  //false
new Number(1) instanceof Number  //true
"hahah" instanceof String //false
new String("hahah") instanceof String //true
null instanceof Object //false
  • 底层机制:只要当前类出现在实例的原型链上的,返回值都为true(基于prototype检测),因此,检测结果可能并不准确
function Fn(){
	this.x = 100;
}
Fn.prototype = Object.create(Array.protptype)
let f = new Fn();
console.log(f instance of Array) //-->true
  • 手写instanceof

方法三

  • constructor支持基本类型
  • 但也能修改,所以也不准确
("1").constructor === String  //true
({}).constructor === Object //true 
([]).constructor === Array //true
([]).constructor === Object //false

方法四

  • Object.prototype.toString.call()标准检测数据类型的方法
  • 不是转化为字符串,时返回当前实例所属类型
let obj = { a:12 }
obj.toString() //=>[object Object]
Object.prototype.toString.call()

Object.prototype.toString.call(NaN)  //->[object NaN]
Object.prototype.toString.call(null)  //=>[object null]
自己封装
(function(){
    var class2type = {};
    var toStirng = class2type.toStirng;

    ["Boolean","Number","String","Function","Array","Date","RegExp","Object","Error","Symbol"]
    .forEach(name => {
        class2type[`[object ${name}]`] = name.toLowerCase;
    })

    function toType(obj){
        if(obj==null) return obj+"";
        return typeof obj==="object" || typeof obj==="function"?
            class2type[toString.call(obj)] ||"object";
            typeof obj;
    }

    window.toType = toType
})()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值