beautypg.com

Loops, Arrays – Multichannel Systems Roboocyte2 JavaScript Manual User Manual

Page 4

background image

>=

greater or equal

x >= 2

<

less

x < 2

<=

less or equal

x <= 2

Loops
With loops it is possible to repeatedly execute parts of the script. There are two kinds of loops:

1. For loop: This is normally used if the number of repetitions is fixed or known in a variable.

The for loop is started with the keyword

for

, followed by three expressions within parenthesis

and a statement block within

{}

:

for (initial-expression; condition; increment-expression)
{

statements

}

The

initial-expression

initializes the counting variable, the

condition

defines when the

loop is to be finished, the

increment-expression

is used to increment the counting variable in

each cycle of the loop.

2. While loop: The number of repetitions need not be known at the time of writing the script, the

loop is terminated by a condition which is usually calculated at the time when the script is
executed only. The syntax is similar to an

if

statement: The keyword

while

is followed by a

condition and a statement block within

{}

:

while (condition)
{
statements
}

With the keyword

break

the loops can be terminated at any time. When

break

is excuted, the loop is

aborted and script execution continues after the loop code block.
With the keyword

continue

, the code inside a loop can be skipped. When

continue

is excuted, the

script immediately continues

Arrays
Arrays are used to store several values in one variable. There are two ways to create an array variable:

1. via the new keyword:

var TestArray = new Array();

or

var TestArray = new Array(1,

2, 3, 4);

2. via square brackets:

var TestArray2 = [1, 2, 3, 4];

The values are stored in the array by using an index, starting with 0 for the first entry in the array. The
length of an array is determinded dynamically: It is the index + 1 of the last defined value in the array.
Values in the arra can be of all available data types: numbers, strings, even other arrays
Several operations are possible on arrays:

length

property: get the number of elements in the array

square brackets

[]

: set or retrieve values by index

t

oString()

: gets a text representation of all values

push(value)

: add value to the end of the array

pop()

: retrieve and remove last value