Creating array elements

A loop can be of a real help in creation of the elements of an array.

For example, if you need to input the names of students of a class then you can use a for loop.

var NumberUser = new Array(4);
for (var count=0 ; count<4 ; count++) {
	NumberUser[count] = window.prompt("Enter your name" , "");
}

First, this code creates a new array that has four elements. The for loop is used to assign each element in the array a value.

The loop starts by setting the loop's count variable to 0 and it will run until the expression count<4 is no longer true.

The count variable will have the value of 0 first time. The value increases by 1 since the count++ adds 1 to the value each time, therefor the value second time will be 1, the third time will be 2, and the forth time will be 3. It won't be a fifth time because that means count will be 4 and it has to be less than 4.

A value is assigned to the element at the index number represented by the count variable each time through. The value that is assigned is what the viewer types in when the prompt appears. In our case the viewer gets four prompts.

Assigning values to elements of an array with loops can be really useful when you want an element value to affect each other element of the array.

var NumberEven = new Array(5);
var StartsCount = 0;
for (var count=0 ; count<10 ; count+=2) {
	NumberEven[StartsCount] = count+2;
	StartsCount ++;
}

On the first line an array with five elements is created.

On the second line, a new variable is declared, which will hold a count incremented by 1.

On the third line the for loop will increment by 2, from 0 to 8.

The forth line assigns elements to the array based on the value of the count variable.

On the fifth line the StartsCount variable is incremented.

The count is increased by 2 to ensure that an even number is used for calculation.

Leave a Reply