Skip to main content

JavaScript: Check if object is array?


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. Then I can loop over it without fear of an error.



So how do I check if the variable is an array?


Source: Tips4allCCNA FINAL EXAM

Comments

  1. 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 );




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

    ReplyDelete
  2. 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

    ReplyDelete
  3. jQuery also offers an isArray method:

    var a = ["A", "AA", "AAA"];

    if($.isArray(a)) {
    alert("a is an array!");
    } else {
    alert("a is not an array!");
    }

    ReplyDelete
  4. You can try this approach: http://www.ajaxdr.com/code/javascript-version-of-phps-is_array-function/

    EDIT: also, if you are already using JQuery in your project, you can use its function $.isArray().

    ReplyDelete
  5. If the only two kinds of values that could be passed to this function are a string or an array of strings, keep it simple and use a typeof check for the string possibility:

    function someFunc(arg) {
    var arr = (typeof arg == "string") ? [arg] : arg;
    }

    ReplyDelete
  6. The best solution I've seen is a cross-browser replacement for typeof. Check Angus Croll's solution here.

    The TL;DR version is below, but the article is a great discussion of the issue so you should read it if you have time.

    Object.toType = function(obj) {
    return ({}).toString.call(obj).match(/\s([a-z|A-Z]+)/)[1].toLowerCase();
    }
    // ... and usage:
    Object.toType([1,2,3]); //"array" (all browsers)

    // or to test...
    var shouldBeAnArray = [1,2,3];
    if(Object.toType(shouldBeAnArray) === 'array'){/* do stuff */};

    ReplyDelete
  7. I know, that people are looking for some kind of raw javascript approach.
    But if you want think less about, take a look here: http://documentcloud.github.com/underscore/#isArray

    isArray_.isArray(object)


    Returns true if object is an Array.

    (function(){ return _.isArray(arguments); })();
    => false
    _.isArray([1,2,3]);
    => true

    ReplyDelete
  8. You could try checking if the object in question has an array method as one of its methods such as push or slice. This doesn't guarantee absolutely that it is an array, but objects that have methods with those names are probably going to be arrays.

    var a = [];
    var b = {};

    if ((a.slice) && (a.slice === function))
    {
    alert ('A is an array');
    }
    else
    {
    alert ('A is not an array');
    }

    if ((b.slice) && (b.slice === function))
    {
    alert ('B is an array');
    }
    else
    {
    alert ('B is not an array');
    }


    Beware, however, this method can be defeated if you have a non-array object that happens to implement a slice methods.

    b.slice = function (){}

    if ((b.slice) && (b.slice === function))
    {
    alert ('B is an array');
    }
    else
    {
    alert ('B is not an array');
    }

    ReplyDelete

Post a Comment

Popular posts from this blog

Wildcards in a hosts file

I want to setup my local development machine so that any requests for *.local are redirected to localhost . The idea is that as I develop multiple sites, I can just add vhosts to Apache called site1.local , site2.local etc, and have them all resolve to localhost , while Apache serves a different site accordingly.