Game Development Reference
In-Depth Information
This walks through all the elements in the array and adds 10 to each. So, after this code is executed,
intArray refers to [14, 23, 25, 26, 33, 52, 7] .
In addition to initializing an array in the way you just saw, there is another way to create an array,
as follows:
var anotherArray = new Array(3);
This example creates an array of size 3, which you can then fill:
anotherArray[0] = "hello";
You can even create multidimensional arrays in JavaScript. For example:
var tictactoe = new Array(3);
tictactoe[0] = ['x', 'o', ' '];
tictactoe[1] = [' ', 'x', 'o'];
tictactoe[2] = [' ', 'o', 'x'];
So, elements of arrays can also be arrays. These kinds of grid structures are especially useful when
representing a playing field in games such as chess. Because arrays are stored as references (just
like instances of classes), representing a grid using such a two-dimensional array is computationally
not very efficient. There is a simple way to represent a grid using a one-dimensional array, as follows:
var rows = 10, cols = 15;
var myGrid = new Array(rows * cols);
Accessing the element at row i and column j can now be done as follows:
var elem = myGrid[i * cols + j];
Figure 13-2 shows another part of the expression syntax diagram, with the syntax for specifying an
array. The next chapter talks more in detail about using arrays to represent structures and grids
in games.
expression
new
type name
expression
.
method name
(
expression
)
,
property name
[
expression
]
,
Figure 13-2. Partial syntax diagram of expressions
 
 
Search WWH ::




Custom Search