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

Why is this Javascript much *slower* than its jQuery equivalent?

I have a HTML list of about 500 items and a "filter" box above it. I started by using jQuery to filter the list when I typed a letter (timing code added later): $('#filter').keyup( function() { var jqStart = (new Date).getTime(); var search = $(this).val().toLowerCase(); var $list = $('ul.ablist > li'); $list.each( function() { if ( $(this).text().toLowerCase().indexOf(search) === -1 ) $(this).hide(); else $(this).show(); } ); console.log('Time: ' + ((new Date).getTime() - jqStart)); } ); However, there was a couple of seconds delay after typing each letter (particularly the first letter). So I thought it may be slightly quicker if I used plain Javascript (I read recently that jQuery's each function is particularly slow). Here's my JS equivalent: document.getElementById('filter').addEventListener( 'keyup', function () { var jsStart = (new Date).getTime()...

Is it possible to have IF statement in an Echo statement in PHP

Thanks in advance. I did look at the other questions/answers that were similar and didn't find exactly what I was looking for. I'm trying to do this, am I on the right path? echo " <div id='tabs-".$match."'> <textarea id='".$match."' name='".$match."'>". if ($COLUMN_NAME === $match) { echo $FIELD_WITH_COLUMN_NAME; } else { } ."</textarea> <script type='text/javascript'> CKEDITOR.replace( '".$match."' ); </script> </div>"; I am getting the following error message in the browser: Parse error: syntax error, unexpected T_IF Please let me know if this is the right way to go about nesting an IF statement inside an echo. Thank you.