zoukankan      html  css  js  c++  java
  • 如何判断数组与对象

    如何判断[ ]或者{ }

     (1) Array.isArray( ) 

    console.log(Array.isArray([1,2]))    //true
    console.log(Array.isArray({"name":"zl"}))     //false

     (2) Object.prototype.toString

     const a = [1,2,3];
     const b = {"name":"lilei"};
     const c = "hello world";
    console.log(Object.prototype.toString.call(a)); //[object Array] console.log(Object.prototype.toString.call(b)); //[object Object] console.log(Object.prototype.toString.call(c)); //[object String]

    使用apply的方法也可以;

    (3)用instanceof判断

    const a = [];
    const b = {};
    console.log(a instanceof Array)    //true
    console.log(a instanceof Object)    //true
    console.log(b instanceof Array)   //false
     

    由于typeof null, 数组,对象的返回值都是object,因此不能用来判断;

    const a = [];
    const b = {}; const c = null; console.log(typeof a); //object console.log(typeof b); //object console.log(typeof c); //object

    (4)用constructor判断

    实例化的数组拥有constructor属性,指向其原型对象。

    const a  = [];
    console.log(a.constructor);//function Array(){[native code]}
    const b = {};
    console.log(b.constructor);//function Object(){[native code]}
    const c = null;
    console.log(c.constructor);// Cannot read property 'constructor' of null

    有一个缺点:就是当我们修改constructor的时候就会发生改变;

    const a = [];
    a.constructor = Object;
    console.log(a.constructor == Array);//false
    console.log(a.constructor == Object);//true
    console.log(a instanceof Array);//true(拥有孙悟空的火眼金睛)

    (5)用Object.prototype.isPrototypeOf判断

    
    

    const a = [];
    const b = {};
    const c = null;

    console.log(Array.prototype.isPrototypeOf(a)) //true

    console.log(Array.prototype.isPrototypeOf(b)) //false

    console.log(Array.prototype.isPrototypeOf(c)) //false

    (6)用getPrototypeOf判断

    console.log(Object.getPrototypeOf(a) === Array.prototype)  //true
    console.log(Object.getPrototypeOf(b) === Array.prototype)  //false
    console.log(Object.getPrototypeOf(c) === Array.prototype)  //cannot convert undefined or null to object 无法转化为对象

    其实许多的内容都可以从网上找到答案,也许很多人都遇到过这样的问题。我是那个需要亲自动手,实践才能搞明白的。嘻嘻。每天加油,继续进步。

  • 相关阅读:
    类欧几里得入土总结 2
    【题解】AGC012C Tautonym Puzzle(人类智慧)
    51nod 1847 奇怪的数学题(min25)
    【题解】51nod1575 LCM and GCD (min25筛)
    【题解】P5163 WD与地图 (这题极好)
    Astronomia.cpp
    LOJ6609 无意识的石子堆 加强版 (容斥)
    【题解】AT2273 Addition and Subtraction Hard(DP)
    【题解】Another Coin Weighing Puzzle (构造)
    【题解】P3747 [六省联考2017]期末考试 (单位根反演)
  • 原文地址:https://www.cnblogs.com/naniandongzhi/p/8675353.html
Copyright © 2011-2022 走看看