Javascript Array create and initialize via for loop

Description

Javascript Array create and initialize via for loop

// create (declare) two new arrays
let n1 = new Array( 5 ); // allocate five-element Array
let n2 = new Array(); // allocate empty Array    
        //from   ww w  .j  av  a 2  s .c o  m
// assign values to each element of Array n1  
for ( let i = 0; i < n1.length; ++i )     
   n1[ i ] = i;
                                   
// create and initialize five elements in Array n2
for ( i = 0; i < 5; ++i )
   n2[ i ] = i;

outputArray( "Array n1:", n1 );
outputArray( "Array n2:", n2 );

// output the heading followed by a two-column table 
// containing subscripts and elements of "theArray"  
function outputArray( heading, theArray )
{
   console.log( heading );
   // output the subscript and value of each array element
   for ( let i = 0; i < theArray.length; i++ )        
      console.log( i + ":" + theArray[ i ] );              
}



PreviousNext

Related