数据类型及判断类型的几种方法

undefined与null的区别

  • undefined代表定义未赋值
  • null代表定义并且赋值了,值为null

什么时候给变量赋值为null呢

  • 初始赋值,表明将要赋值为对象
  • 结束前,让对象成为垃圾对象(被垃圾回收器回收)

严格区分变量类型与数据类型

  • 数据的类型
    • 基本类型
      • String:任意字符串
      • Number:任意数字
      • Boolean:true/false
      • Undefined:undefined
      • Null:null
    • 对象类型
      • Object:任意对象
      • Function:一种特别的对象(可以执行)
      • Array:一种特别的对象(数值下标,内部数据是有序的)
      • ……
  • 变量的类型
    • 基本类型:保存的是基本类型的数据
    • 引用类型:保存的是地址值,数据类型是对象类型

判断

  • typeof

    可以判断:undefined/数值/字符串/布尔值/function

    不能判断:null与object,object与array

    对于基本数据类型,返回其本身的数据类型,对于函数返回function,其它对象均返回object

    let a;
    
    console.log(typeof a)	// undefined
    
    a = "123";
    console.log(typeof a);	// string
    
    a = 1;
    console.log(typeof a)	// number
    
    a = true;
    console.log(typeof a)	// boolean
    
    a = null;
    console.log(typeof a)	// object
    
  • instanceof

    判断对象的具体数据类型

    let a = new Date()
    console.log(a instanceof Date)	// true
    
    let b = {}
    console.log(b instanceof Object)	// true
    
    let c = []
    console.log(c instanceof Array)	// true
    
  • ===

    可以判断:undefinednull

    let c;
    console.log(c === undefined)	// true
    
    c = null;
    console.log(c === null)	// true
    
  • Object.prototype.toString()

    可以判断所有数据类型

    let d;
    console.log(Object.prototype.toString.call(d))	// [object Undefined]
    
    d = "";
    console.log(Object.prototype.toString.call(d))	// [object String]
    
    d = 123;
    console.log(Object.prototype.toString.call(d))	// [object Number]
    
    d = true;
    console.log(Object.prototype.toString.call(d))	// [object Boolean]
    
    d = null;
    console.log(Object.prototype.toString.call(d))	// [object Null]
    
    d = {};
    console.log(Object.prototype.toString.call(d))	// [object Object]
    
    d = function(){}
    console.log(Object.prototype.toString.call(d))	// [object Function]
    
    d = [];
    console.log(Object.prototype.toString.call(d))	// [object Array]
    
    d = new Date();
    console.log(Object.prototype.toString.call(d))	// [object Date]
    
    d = new RegExp("123", "i");
    console.log(Object.prototype.toString.call(d))	// [object RegExp]
    
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值