To create a new array, we use an array literal or the new operator (i.e.,
new Array( )).
In an array literal, square brackets demarcate the beginning and end of the array. Inside the square brackets, the values of the array's elements are specified as a comma-separated list. Here's the general syntax:
The expressions are resolved and then assigned to the elements of the array being defined. Any valid expression can be used, including function calls, variables, literals, and even other arrays (an array within an array is called a nested array or a two-dimensional array).
Here are a few examples:
// Simple numeric elements [4, 5, 63]; // Simple string elements ["apple", "orange", "pear"] // Numeric expressions with an operation [1, 4, 6 + 10] // Variable values and strings as elements [firstName, lastName, "tall", "skinny"] // A nested array literal ["month end days", [31, 30, 28]]
To create an array with the new operator, we use the following generalized code:
The result of the preceding code depends on the number and type of arguments supplied to the Array constructor. When more than one argument is supplied, or when a single nonnumeric argument is supplied, each argument becomes one of the element values in the new array. For example, the following code creates an array with three elements:
new Array("sun", "moon", "earth")
When exactly one ...