which is the best method used for checking isarray

This question already has an answer here:

  • How do you check if a variable is an array in JavaScript? [duplicate] 24 answers

  • Big guys (Jquery, underscore) do it like this:

      isArray = Array.isArray || function(obj) {
        return Object.prototype.toString.call(obj) == '[object Array]';
      };
    

    But these are not the droids you're looking for you actually don't need this at all. Don't "check" your variables - just know them.


    Array.IsArray would be better to use.

    Also check this instanceof considered harmful (or how to write a robust isArray )

    The problems arise when it comes to scripting in multi-frame DOM environments. In a nutshell, Array objects created within one iframe do not share [[Prototype]]'s with arrays created within another iframe. Their constructors are different objects and so both instanceof and constructor checks fail:

    Also you can check the speed variation between the two and you will find that isArray is comparatively faster.

    Here is a link to check that:- Array.isArray vs instanceof Array

    Below code is used to check the speed variation:

    <script>
      Benchmark.prototype.setup = function() {
        var a = [1, 2, 3];
        var s = 'example';
        var f = false;
      };
    </script>
    

    Using Array.IsArray:

    (Array.isArray(a) && (Array.isArray(s) || Array.isArray(f)));
    

    it performed nearly 25,255,693 ops/sec

    Now using instanceof:-

     (a instanceof Array && (s instanceof Array || f instanceof Array));
    

    it performed nearly 21,594,618 ops/sec

    ie, instanceOf is 15% slower than using IsArray.

    链接地址: http://www.djcxy.com/p/19298.html

    上一篇: 看看一个变量是否是一个使用JavaScript的数组

    下一篇: 这是用于检查isarray的最佳方法