如何判断一个值为对象类型

  1. 使用typeof判断(不推荐);
    let a = {};
    typeof a; //object
    let a = [];
    typeof a;//object
    let a = null;
    typeof a;//object

    缺点是:使用typeof时,数组和null判断结果都为对象类型所以不推荐

  2. 使用instanceof判断;
    let a = [];
    a instanceof Object;//true
    let a = {};
    a instanceof Object;//true

    缺点是:使用instanceof时,数组也为对象类型

  3. 使用JSON.stringify()判断(推荐);
    let a = {};
    JSON.stringify(a) == "{}";//true

     

     

  4. 使用Object.prototype.toString.call()判断(推荐);
    Object.prototype.toString.call(null)
    '[object Null]'
    
    Object.prototype.toString.call({})
    '[object Object]'

    Object.prototype.toString.call([]) '[object Array]'

    Object.prototype.toString.call("") '[object String]'

    Object.prototype.toString.call(undefined) '[object Undefined]'

    Object.prototype.toString.call(false)
    '[object Boolean]'

     

 

posted on 2023-11-24 10:33  久居我梦  阅读(31)  评论(0编辑  收藏  举报

导航