How to Initialize a JavaScript Array

An array is an ordered set of key/value pairs. In JavaScript, the elements of an array do not have to be of the same type. Arrays can be indexed, where the keys are consecutive integers, or associative, where the keys are strings. Arrays can also contain objects, such as other arrays, as elements. You can initialize an array with the "Array" constructor.

Instructions

    • 1

      Initialize a new array without any elements using the Array constructor. Assign elements to the array as you would assign any variable. For example, type:

      var myArray = new Array();

      myArray[0] = 10;

      myArray[1] = 20;

    • 2

      Initialize an array by passing values to the Array constructor. For example, type:

      var myArray = new Array("Steve", "John", "Paul", "Peter");

    • 3

      Set the number of elements in an array when you initialize it by passing the number as a parameter to the Array construct. For example, type:

      var myArray = new Array(2);

      myArray[0] = 1;

      myArray[1] = 2;

    • 4

      Initialize an array of arrays or objects by calling the array or object constructor for each element. For example, type:

      var myArray = new Array(new Array(10, 20, 30), new Arrray(40, 50, 60));

Related Searches:

References

Comments

You May Also Like

  • How to Initialize an Array

    Arrays are a central part of programming. You will use arrays of one type or another in nearly every program you create....

  • How to Initialize an Empty Array in C

    In programming, coders use variables to store pieces of data to access and manipulate throughout the course of the program. While regular...

  • How to Parse a Query String in JavaScript

    JavaScript does not provide a built-in function to capture the query string passed to a Web page with the URL, as do...

  • How to Initialize an Array

    Initialize an array by creating a program that includes an iostream, an array of integers and an initialization loop. Run the output...

  • How to Use an Array Class in Javascript

    To some, Javascript is often viewed as a primitive and not particularly useful programming language. However, Javascript is actually a fully object-oriented...

Related Ads

Featured