How to check if an object is an array?

后端 未结 30 2940
名媛妹妹
名媛妹妹 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:50

    In modern browsers you can do:

    Array.isArray(obj)
    

    (Supported by Chrome 5, Firefox 4.0, IE 9, Opera 10.5 and Safari 5)

    For backward compatibility you can add the following:

    // only implement if no native implementation is available
    if (typeof Array.isArray === 'undefined') {
      Array.isArray = function(obj) {
        return Object.prototype.toString.call(obj) === '[object Array]';
      }
    };
    

    If you use jQuery you can use jQuery.isArray(obj) or $.isArray(obj). If you use underscore you can use _.isArray(obj).

    If you don't need to detect arrays created in different frames you can also just use instanceof:

    obj instanceof Array
    
    0 讨论(0)
  • 2020-11-21 06:51

    Array.isArray works fast, but it isn't supported by all versions of browsers. So you could make an exception for others and use universal method:

        Utils = {};    
        Utils.isArray = ('isArray' in Array) ? 
            Array.isArray : 
            function (value) {
                return Object.prototype.toString.call(value) === '[object Array]';
            }
    
    0 讨论(0)
  • 2020-11-21 06:51

    I do this in a very simple way. Works for me. Any drawbacks?

    Array.prototype.isArray = true;
    
    a=[]; b={};
    a.isArray  // true
    b.isArray  // (undefined -> false)
    
    0 讨论(0)
  • 2020-11-21 06:51

    I have updated the jsperf fiddle with two alternative methods as well as error checking.

    It turns out that the method defining a constant value in the 'Object' and 'Array' prototypes is faster than any of the other methods. It is a somewhat surprising result.

    /* Initialisation */
    Object.prototype.isArray = function() {
      return false;
    };
    Array.prototype.isArray = function() {
      return true;
    };
    Object.prototype._isArray = false;
    Array.prototype._isArray = true;
    
    var arr = ["1", "2"];
    var noarr = "1";
    
    /* Method 1 (function) */
    if (arr.isArray()) document.write("arr is an array according to function<br/>");
    if (!noarr.isArray()) document.write("noarr is not an array according to function<br/>");
    /* Method 2 (value) - **** FASTEST ***** */
    if (arr._isArray) document.write("arr is an array according to member value<br/>");
    if (!noarr._isArray) document.write("noarr is not an array according to member value<br/>");

    These two methods do not work if the variable takes the undefined value, but they do work if you are certain that they have a value. With regards to checking with performance in mind if a value is an array or a single value, the second method looks like a valid fast method. It is slightly faster than 'instanceof' on Chrome, twice as fast as the second best method in Internet Explorer, Opera and Safari (on my machine).

    0 讨论(0)
  • 2020-11-21 06:52

    The method given in the ECMAScript standard to find the class of Object is to use the toString method from Object.prototype.

    if( Object.prototype.toString.call( someVar ) === '[object Array]' ) {
        alert( 'Array!' );
    }
    

    Or you could use typeof to test if it is a String:

    if( typeof someVar === 'string' ) {
        someVar = [ someVar ];
    }
    

    Or if you're not concerned about performance, you could just do a concat to a new empty Array.

    someVar = [].concat( someVar );
    

    There's also the constructor which you can query directly:

    if (somevar.constructor.name == "Array") {
        // do something
    }
    

    Check out a thorough treatment from @T.J. Crowder's blog, as posted in his comment below.

    Check out this benchmark to get an idea which method performs better: http://jsben.ch/#/QgYAV

    From @Bharath convert string to array using Es6 for the question asked:

    const convertStringToArray = (object) => {
       return (typeof object === 'string') ? Array(object) : object 
    }
    

    suppose:

    let m = 'bla'
    let n = ['bla','Meow']
    let y = convertStringToArray(m)
    let z = convertStringToArray(n)
    console.log('check y: '+JSON.stringify(y)) . // check y: ['bla']
    console.log('check y: '+JSON.stringify(z)) . // check y: ['bla','Meow']
    
    0 讨论(0)
  • 2020-11-21 06:52

    Simple function to check this:

    function isArray(object)
    {
        return object.constructor === Array;
    }
    
    0 讨论(0)
提交回复
热议问题