Arrays in JavaScript

JavaScript arrays are also very similar to those in PHP, in that an array can contain
string or numeric data, as well as other arrays. To assign values to an array, use the
following syntax (which in this case creates an array of strings):

To create a multidimensional array, nest smaller arrays within a larger one. So, to create a two-dimensional array containing the colors of a single face of a scrambled Rubik’s Cube (where the colors red, green, orange, yellow, blue, and white are represented by their capitalized initial letters), you could use the following code.

face =
['R', 'G', 'Y'],
['W', 'R', 'O'],
['Y', 'W', 'G']

The previous example has been formatted to make it obvious what is going on, but it could also be written like this:

face = [['R', 'G', 'Y'], ['W', 'R', 'O'], ['Y', 'W', 'G']]

or even like this:

top = ['R', 'G', 'Y']
mid = ['W', 'R', 'O']
bot = ['Y', 'W', 'G']
face = [top, mid, bot]

To access the element two down and three along in this matrix, you would use the following (because array elements start at position zero):


This statement will output the letter O for orange.


You may also like...