zoukankan      html  css  js  c++  java
  • 面试题系列---【js如何判断一个对象是数组】

    js如何判断一个对象是数组

    1.typeof操作符

    利用typeof除了array和null判断为object外,其他的都可以正常判断

    2.instanceof操作符

    var arr = [1,2,3,1];
    console.log(arr instanceof Array); // true
    
    var fun = function(){};
    console.log(fun instanceof Function); // true
    

    3.对象的constructor 属性

    var arr = [1,2,3,1];
    console.log(arr.constructor === Array); // true
     
    var fun = function(){};
    console.log(arr.constructor === Function); // true
    

    4.使用 Object.prototype.toString 来判断是否是数组

    Object.prototype.toString.call( [] ) === ``'[object Array]'` `// true` Object.prototype.toString.call( ``function``(){} ) === ``'[object Function]'` `// true
    

    这里使用call来使 toString 中 this 指向 obj。进而完成判断 

    5.Array.isArray()

    Array.isArray([])  ``// true
    

    6.使用 原型链 来完成判断

    [].__proto__ === Array.prototype ``// true` `var` `fun = ``function``(){}``fun.__proto__ === Function.prototype ``// true
    
  • 相关阅读:
    js
    DOM
    css
    html
    java虚拟机
    java并发
    java容器
    java基础
    计算机网络面试题
    计算机操作系统-设备管理
  • 原文地址:https://www.cnblogs.com/chenhaiyun/p/14916493.html
Copyright © 2011-2022 走看看