zoukankan      html  css  js  c++  java
  • 判断数组的方法

    1.Array.prototype.isPrototypeOf(arr)

    判断Array是否在arr的原型链上,返回布尔类型,如果存在返回true,否则返回false

    1   console.log(Array.prototype.isPrototypeOf([])); //true
    2   console.log(Array.prototype.isPrototypeOf({})); //false
    3 
    4   const arr = [1,2,3]
    5   console.log(Array.prototype.isPrototypeOf(arr));  //true
    1   const arr = []
    2   console.log(arr);
    3   console.log(Array.prototype.isPrototypeOf(arr));  //true
    4   console.log(Object.prototype.isPrototypeOf(arr));  //true
    5
    console.log(arr.constructor == Array); //true
    6 console.log(arr.constructor == Object); /false
    
    

     

    2.instanceof

    instanceof()判断前者是否继承自后者

    1   console.log([] instanceof Array); //true
    2   console.log({} instanceof Array); //false

    补充:

    1   function Aoo() { }
    2   function Foo() { }
    3   Foo.prototype = new Aoo();//FOO类继承自AOO类
    4 
    5   var f = new Foo();
    6   console.log(f);
    7   console.log(f instanceof Foo)//true 
    8   console.log(f instanceof Aoo)//true

    3.Object.prototype.toString.call()

    每一个继承 Object 的对象都有 toString方法,如果 toString 方法没有重写的话,会返回 [Object type],其中 type 为对象的类型。

    但当变量类型不为对象时,使用 toString 方法会直接返回数据内容的字符串,所以我们需要使用call或者apply方法来改变toString方法的执行上下文。

     1   const arr = ['kujo', 'jotaro']
     2   const str = 'kujo jotaro'
     3   const obj = {
     4     firstname: 'jotaro',
     5     lastname: 'kujo'
     6   }
     7   const bol = false
     8   
     9   console.log(arr.toString())
    10   console.log(obj.toString())
    11   console.log(Object.prototype.toString.call(arr))
    12   console.log(Object.prototype.toString.call(str))
    13   console.log(Object.prototype.toString.call(obj))
    14   console.log(Object.prototype.toString.call(bol))

    4.Array.isArray()

    1   console.log(Array.isArray([])) //true
    2   console.log(Array.isArray({})) //false
    3   console.log(Array.isArray('jojo')) //false
  • 相关阅读:
    shell入门-sed-2替换功能
    shell入门-sed-1
    shell入门-grep-3-egrep
    shell入门-grep2
    shell入门-grep过滤-1
    shell入门-连接符(并且、和、或者)
    shell入门-tr替换字符和split切割大文件
    shell入门-uniq去重复和tee重定向
    class类的相关操作 --| 公有普通方法 | 私有普通方法 | 无参方法 | 有参方法
    类的封装性-- | 成员属性 | 成员方法 | 私有属性 | 私有方法 之间调用
  • 原文地址:https://www.cnblogs.com/memeflyfly/p/14310371.html
Copyright © 2011-2022 走看看