In: Computer Science
Activity 12: Array
What is an Array?
An array is a special variable, which can hold more than one value
at a time.
If you have a list of items (a list of car names, for example),
storing the cars in single variables could look like this:
var car1 = "Saab"; var car2 =
"Volvo";
var car3 = "BMW";
However, what if you want to loop through the cars and find a
specific one? And what if you had not 3 cars, but 300?
The solution is an array!
An array can hold many values under a single name, and you can
access the values by referring to an index number.
Syntax: var array-name = [item1, item2,
...];
Example: var cars = ["Saab", "Volvo", "BMW"];
Arrays are allocated using the new keyword.
Array indexes start at 0 and extend to the size of the array minus
1. To assign a value to an element of an array open and close
brackets are used.
The size of an array can be increased dynamically by assigning a
value to an element pass the end of the array. Array can be created
that initially has no elements at all. In addition, they are not of
a fixed size but can grow dynamically.
The array, pictures, initially has no elements. After "Mona Lisa"
has been assigned the array has 36 elements. The unassigned
elements are set to Undefined.
The length property of arrays returns the number of elements in the
array.
Tasks 1
Create an array of 5 animals. Use for loop to list values in the
array.
1. Go through the lecture slides and understand arrays and
multidimensional arrays.
2. Define a function max() that takes two numbers as arguments and
returns the largest of them. Use the if-then-else construct
available in Javascript.
For tasks 1, the array and the required function has been coded below, Some comment lines are also used in the code to state what the code is doing. In case of any query, you can mention it in the comment section. HAPPY LEARNING!!
For getting the output, you need to put the javascript code under html tags and save it with the extension .html and open it with any browser.
CODE:
<html>
<script>
var animals = new Array("Cat","Dog","Human","Elephant","Horse"); // created the array of animals dynamically using new keyword
var listed_animals = "";
for (var i = 0; i < animals.length; i++) {
listed_animals += animals[i] + " "; // accessing the values of array by for loop and concatenating in a single string separated by space
}
document.write("<b>Listed animals are: </b>");
document.write(listed_animals); // written the listed animals on the page
function Max(x,y) { // function definition
if (x>y){ // checking if x is greater than y
return x;
}
else if (x<y){ // if x is less than y
return y;
}
else{ // else both are equal
return "Both are equal";
}
}
document.write("<p>The biggest in 12 and -34 is"+Max(12,-34)+"</p>");
</script>
</html>
OUTPUT(SCREENSHOT OF OUTPUT IN CHROME BROWSER):