Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Javascript: How to Recognize if a variable is an array?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 117
    Comment on it

    In Javascript there are several ways to detect array(variable is an array). But through this post , I will tell you ony four different ways to detect variable is an array .
    Below there are 4 different ways are :->
    1) Array.isArray(object) -> obj will be checked .
    Example ->
    // right syntax which return true ->

     Array.isArray([ ]);<br>
        Array.isArray([ 1 ]);<br>
        Array.isArray([ new Array ]);<br>
        Array.isArray([ ]);<br>
        Array.isArray([ Array.prototype]); // Array.prototype itself is also an array
    


    // wrong syntax which return false ->

      Array.isArray( );<br>
        Array.isArray({ });<br>
        Array.isArray( [ null ] );<br>
        Array.isArray( undefined );<br>
        Array.isArray( 20 );Array.isArray([ ]);<br>
        Array.isArray( Array );<br>
        Array.isArray( true );<br>
        Array.isArray( false );<br><br>
    

    suppose if Array.isArray() is not availbale, then you can make a function to create Array.isArray() method.
    code to create function is ->

    if ( !Array.isArray)<br>
    {<br>
               Array.isArray = function( argument/object )<br>
                   return Object.prototype.toString.call( argument ) == '[ object Array ] ' ;<br>
    };<br>
    }<br><br>
    

    2) using constructor checking
    Example ->

    function isArray( obj ){<br>
      return( typeof obj !== 'undefined' && obj && obj.constructor === Array ) // (===) will check the value as well as data type alos<br>
    

    Note -> Constructor checking is very fast and accurate .But it fail to identify when it is inherited from an Array

    3) using instanceof operator
    Example ->

    fuction isArray(obj){
        return obj instanceof Array ;<br>
    }<br><br>
    

    4) using Prototype toString check
    Example ->

           isArray = function(obj){<br>
               return Object.prototype.toString.call(obj) =="[ object Array ] " ;<br>
    }
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: