Whats the best way to find out if an Object is an Array

后端 未结 4 1520
北荒
北荒 2021-02-13 21:07

As far as I know there are three ways of finding out if an object is an Array

by isArray function if implemented

Array.isArray()
         


        
4条回答
  •  天命终不由人
    2021-02-13 21:46

    The best way is probably to use the standard Array.isArray(), if it's implemented by the engine:

    isArray = Array.isArray(myObject)
    

    MDN recommends to use the toString() method when Array.isArray isn't implemented:

    Compatibility

    Running the following code before any other code will create Array.isArray if it's not natively available. This relies on Object.prototype.toString being unchanged and call resolving to the native Function.prototype.call method.

    if(!Array.isArray) {  
      Array.isArray = function (arg) {  
        return Object.prototype.toString.call(arg) == '[object Array]';  
      };  
    }
    

    Both jQuery and underscore.js[source] take the toString() === "[object Array]" way.

提交回复
热议问题