Friday, March 20, 2009

Creating arrays in javascript

Arrays are so handy that you’ll often want to create your own.for example, A phone book is an array of names and phone numbers. You can think of a survey as an array of questions; an array can also store the answers a visitor enters. A slide show is an array of pictures shown in sequence.

JavaScript lets you create your own arrays. If you know what
you want to store in the array when you create it, use a line like the following:

Array Declaration:
var colors =new Array("red", "orange", "yellow", "green", "blue", "indigo", "violet");

This line creates a variable called rainbow_colors that stores an array of colors.
The words new Array() tell JavaScript to create a new Array object.To put values in your new array, simply list them in the parentheses.

Example:

<html>
<head>
<title>Strobe</title>
<script type = "text/javascript">

function strobeIt()
{
var colors =
new Array("red", "orange", "yellow", "green", "blue", "indigo", "violet");
var index = 0;
while (index < rainbow_colors.length)
{
window.document.bgColor = colors[index];
index++;
}
}

</script>
</head>
<body>
<form>
<input type = "button" value = "strobe" onClick = "strobeIt();">
</form>
</body>
</html>

creates the array and sets up the loop, saying, “While index is less than the number of items in the array, execute the JavaScript between the curly brackets.” The first time through the loop, index is 0, so when looks up rainbow_colors[index], it gets the first item in the array, the value red. Line assigns this value to window.document.bgColor, which sets the background color to red. Once the script has set this color, adds 1 to index, and the loop begins again. Next time through, index will be 1, so will make the background color orange, then adds 1 to index, making it 2, and back through the loop we go. If you have a very fast computer, the background
may strobe too quickly for you to see it. In this case, add a few more colors
to the array in.

No comments:

Post a Comment