javascript 数据类型检测

数据类型检测

  1. typeof

    常用于检测基本数据类型

    • 不能区分 null 和引用数据类型
    typeof 'hello';		// string
    typeof('hello');	// string
    
    // 注意
    typeof null;	// object
    typeof [];		// object
    typeof {};		// object
    
  2. instanceof

    常用于检测引用数据类型(特别是自定义类型)

    • 不能用于检测基本数据类型字面量
    • 原型链上的父类都会使得 instanceof 为 true
    let o = {};
    o instanceof Object;	// true
    let arr = [];
    arr instanceof Array;	// true
    
    // 注意
    1 instanceof Number;	// false
    
  3. 构造函数法

    let arr = [];
    arr.constructor === Array;	// true
    
  4. 使用最原始toString()方法(返回[object type])判断数据类型

    常用于检测内置对象

    // Object.prototype.toString.call()
    
    // 基本数据类型
    Object.prototype.toString.call(null);		// [object Null]
    Object.prototype.toString.call(undefined);	// [object Undefined]
    Object.prototype.toString.call(1);			// [object Number]
    Object.prototype.toString.call(false);		// [object Boolean]
    Object.prototype.toString.call('string');	// [object String]
    Object.prototype.toString.call(Symbol('symbol'));	// [object Symbol]
    
    // 内部引用数据类型
    Object.prototype.toString.call([1,2,3]);	// [object Array]
    Object.prototype.toString.call(() => {});	// [object Function]
    Object.prototype.toString.call(new Date());	// [object Date]
    Object.prototype.toString.call(new RegExp());	// [object RegExp]
    
    // 自定义引用数据类型
    function Persion(_name='name', _age=18){
    	this.name = _name;
    	this.age = _age;
    }
    Object.prototype.toString.call(new Persion('girl'));	// [object Object]
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值