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

[韓日関係] 首相含む大幅な内閣改造の可能性…早ければ来月10日ごろ=韓国

div not scrolling properly with slimScroll plugin

I am using the slimScroll plugin for jQuery by Piotr Rochala Which is a great plugin for nice scrollbars on most browsers but I am stuck because I am using it for a chat box and whenever the user appends new text to the boxit does scroll using the .scrollTop() method however the plugin's scrollbar doesnt scroll with it and when the user wants to look though the chat history it will start scrolling from near the top. I have made a quick demo of my situation http://jsfiddle.net/DY9CT/2/ Does anyone know how to solve this problem?

Why does this javascript based printing cause Safari to refresh the page?

The page I am working on has a javascript function executed to print parts of the page. For some reason, printing in Safari, causes the window to somehow update. I say somehow, because it does not really refresh as in reload the page, but rather it starts the "rendering" of the page from start, i.e. scroll to top, flash animations start from 0, and so forth. The effect is reproduced by this fiddle: http://jsfiddle.net/fYmnB/ Clicking the print button and finishing or cancelling a print in Safari causes the screen to "go white" for a sec, which in my real website manifests itself as something "like" a reload. While running print button with, let's say, Firefox, just opens and closes the print dialogue without affecting the fiddle page in any way. Is there something with my way of calling the browsers print method that causes this, or how can it be explained - and preferably, avoided? P.S.: On my real site the same occurs with Chrome. In the ex