美文网首页js基础
js判断变量是否是数组的方法总结

js判断变量是否是数组的方法总结

作者: sansan大王 | 来源:发表于2019-02-13 19:10 被阅读0次

    判断是否是数组的几种方法:

    1. instanceof 

         原理是通过判断左操作数的对象的原型链上是否具有右操作数的构造函数的prototype属性。

         [] instanceof Array  // true

          let a = {}; a instanceof Array // false

    * typeof [] === 'object'  // true

    2.Array.isArray

        这个ES5新增的一个Array方法,该方法是Array对象的一个静态函数,用来判断一个对象是不是数组。

         Array.isArray([1,2,3]);// true

    3. constructor 

        [].constructor === Array  // true

        [].constructor.name === 'Array'   // true

    4. Object.prototype

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

    5.Function.prototype

       let arr = Function.prototype.call.bind(Object.prototype.toString)

       toStr([]) === '[object Array]'  // true

     6. 原型prototype + isPrototypeOf()

    isPrototypeOf() 函数 : 用于指示对象是否存在于一个对象的原型链中。如果存在返回true,反之返回false。该方法属Object对象,由于所有的对象都继承了Object的对象实例,因此几乎所有的实例对象都可以使用该方法。如果variable的原型链中存在Array对象,就会返回true,也就说明var是数组类型

       Array.prototype.isPrototypeOf([])  // true

      Array.prototype.isPrototypeOf({}) // false 

    相关文章

      网友评论

        本文标题:js判断变量是否是数组的方法总结

        本文链接:https://www.haomeiwen.com/subject/tazdeqtx.html