2020年大前端面试题库+答案(第3章) javaScript判断对象类型

888 阅读2分钟

1.typeof

typeof只能判断区分基本类型,如:number、string、boolean、undefined和object、function

    typeof 0; //number
    typeof true; //boolean
    typeof undefined; //undefined
    typeof "hello world"; //string
    typeof function(){}; //function
    
    typeof null; //object
    typeof {}; //object
    typeof []; //object

从上面可以看出,typeof 判断对象和数组都返回object,因此它无法区分对象和数组。

2.instanceof

    var a = {};
    a instanceof Array //false
    a instanceof Object //true
    var b = []
    b instanceof Array //true
    b instanceof Object //true

因为数组属于Object的一种, 所以[] instanceof object,也是成立的。

    var c = 'abc';
    c instanceif String //false
    var d = new String();
    d instanceof String //true

instanceof 不能区分基本类型string 和 boolean,除非是字符串对象和布尔对象。 如上例所示。

3.constructor

    var o = {};
    o.constructor == Object //true
    var arr = [];
    arr.constructor == Array // true
    arr.constructor == Object //false

可以看出constructor可以区分Array和Object.

    var n = true;
    n.constructor == Boolean //true
    var num = 1;
    num.constructor == Number //true
    var str = 'hello world'
    str.constructor == String
    
    var num = new Number();
    
    num.constructor == Number //true

不过要注意,constructor 属性是可以被修改的,会导致检测出的结果不正确

    function Person(){}
    function Student(){}
    Student.prototype = new Person();
    var John = new Student();
    console.log(John.constructor == Student) //false
    console.log(john.constructor == Person) //true

除了undefined 和 null,其他类型变量均能使用constructor判断出类型.

4.Object.prototype.toString.call()------------最好用

Object.prototype.toString.call(123) //"[object Number]"

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

object.prototype.toString.call('true')  //"[object Boolean]"

object.prototype.toString.call({})  //"[object Object]"

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

这里可以封装一个判断数组和对象的方法

    function typeObj(obj){
        var type = Object.prototype.toString.call(obj);
        if(type == '[object Array]'){
            return "Array"
        }else if(type == "[object Object]"){
            return "Object"
        }else{
            return "obj is not object or array"
        }
    }

Object.prototype.toString()方法在被调用的时候,会执行如下的操作步骤:

  • 1.获取对象的类名 (对象类型)
    [[Class]]是一个内部属性,所有的对象(原生对象和宿主对象)都有该属性,在规范中,[[Class]]是这么定义的:
    内部属性,[[Class]] 一个字符串值,表明该对象的类型。
  • 2.然后将[object 获取的对象类型的名] 组合为字符串
  • 3.返回字符串 "[object Array]"

5.jQuery中的$.type接口

  • $.type(obj)
  • $.isArray(obj)
  • $.isFunction(obj)
  • $.isPlainObjext(obj)
    $.type([]) //array
    $.isArray([]) //true
    $.isFunction(function(){}) true
    $.isPlainObject({}) //true
    $.isPlanObject([]) //false

每章语录:不要吹灭你的灵感和你的想象力; 不要成为你的模型的奴隶。
——文森特・梵高
摘自:cnblogs.com/sunmarvell/…