How to check if an object is an array?

后端 未结 30 2880
名媛妹妹
名媛妹妹 2020-11-21 06:31

I\'m trying to write a function that either accepts a list of strings, or a single string. If it\'s a string, then I want to convert it to an array with just the one item so

相关标签:
30条回答
  • 2020-11-21 06:53

    Imagine you have this array below:

    var arr = [1,2,3,4,5];
    

    Javascript (new and older browsers):

    function isArray(arr) {
      return arr.constructor.toString().indexOf("Array") > -1;
    }
    

    or

    function isArray(arr) {
      return arr instanceof Array;
    }
    

    or

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

    then call it like this:

    isArray(arr);
    

    Javascript (IE9+, Ch5+, FF4+, Saf5+, Opera10.5+)

    Array.isArray(arr);
    

    jQuery:

    $.isArray(arr);
    

    Angular:

    angular.isArray(arr);
    

    Underscore and Lodash:

    _.isArray(arr);
    
    0 讨论(0)
  • 2020-11-21 07:00

    You could is isArray method but I would prefer to check with

    Object.getPrototypeOf(yourvariable) === Array.prototype

    0 讨论(0)
  • 2020-11-21 07:01

    You can check the type of your variable whether it is an array with;

    var myArray=[];
    
    if(myArray instanceof Array)
    {
    ....
    }
    
    0 讨论(0)
  • 2020-11-21 07:01
    A = [1,2,3]
    console.log(A.map==[].map)
    

    In search for shortest version here is what I got so far.

    Note, there is no perfect function that will always detect all possible combinations. It is better to know all abilities and limitations of your tools than expect a magic tool.

    0 讨论(0)
  • 2020-11-21 07:03

    I would first check if your implementation supports isArray:

    if (Array.isArray)
        return Array.isArray(v);
    

    You could also try using the instanceof operator

    v instanceof Array
    
    0 讨论(0)
  • 2020-11-21 07:05

    I would make a function to test the type of object you are dealing with...

    function whatAmI(me){ return Object.prototype.toString.call(me).split(/\W/)[2]; }
    
    // tests
    console.log(
      whatAmI(["aiming","@"]),
      whatAmI({living:4,breathing:4}),
      whatAmI(function(ing){ return ing+" to the global window" }),
      whatAmI("going to do with you?")
    );
    
    // output: Array Object Function String

    then you can write a simple if statement...

    if(whatAmI(myVar) === "Array"){
        // do array stuff
    } else { // could also check `if(whatAmI(myVar) === "String")` here to be sure
        // do string stuff
    }
    
    0 讨论(0)
提交回复
热议问题