总结判断数据类型的几种方法

准备数据类型

<!DOCTYPE html>
<html lang="en">

    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>

    <body>

    </body>

</html>
<script>
    let a = "string";
    let b = 111;
    let c = {};
    let d = [1, 2, 3];
    let e = function () {
        console.log("eee");
    }
    let f = undefined;
    let g = null;
    let h = new Date();
    let i = /test/;
    let j = true;
</script>

用typeof()判断()

console.log(typeof(a),typeof(b),typeof(c),typeof(d),typeof(e),typeof(f),typeof(g),typeof(h),typeof(i),typeof(j))

结果

用instanceof判断

    console.log(a instanceof String);//false
    console.log(b instanceof Number);//false
    console.log(c instanceof Object);//true
    console.log(d instanceof Array);//true
    console.log(e instanceof Function);//true
    console.log(h instanceof Date);//true
    console.log(i instanceof RegExp);//true

用constructor判断

    console.log(c.constructor===Object);//true
    console.log(d.constructor===Array);//true
    console.log(e.constructor===Function);//true
    console.log(h.constructor=== Date);//true
    console.log(i.constructor=== RegExp);//true

用Object.prototype.toString.call()判断

    console.log(Object.prototype.toString.call(a) === '[object String]');//true
    console.log(Object.prototype.toString.call(b) === '[object Number]');//true
    console.log(Object.prototype.toString.call(c) === '[object Object]');//true
    console.log(Object.prototype.toString.call(d) === '[object Array]');//true
    console.log(Object.prototype.toString.call(e) === '[object Function]');//true
    console.log(Object.prototype.toString.call(f) === '[object Undefined]');//true
    console.log(Object.prototype.toString.call(g) === '[object Null]');//true
    console.log(Object.prototype.toString.call(h) === '[object Date]');//true
    console.log(Object.prototype.toString.call(i) === '[object RegExp]');//true

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值