Activity 12: Array What is an
Activity 12: ArrayWhat is an Array?An array is a special variable, which can hold more than one valueat 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 aspecific 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 canaccess 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 minus1. To assign a value to an element of an array open and closebrackets are used.The size of an array can be increased dynamically by assigning avalue to an element pass the end of the array. Array can be createdthat initially has no elements at all. In addition, they are not ofa 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 unassignedelements are set to Undefined.The length property of arrays returns the number of elements in thearray.Tasks 1Create an array of 5 animals. Use for loop to list values in thearray.1. Go through the lecture slides and understand arrays andmultidimensional arrays.2. Define a function max() that takes two numbers as arguments andreturns the largest of them. Use the if-then-else constructavailable in Javascript.
Answer:
For tasks 1, the array and the required function has been codedbelow, Some comment lines are also used in the code to state whatthe code is doing. In case of any query, you can mention it in thecomment section. HAPPY LEARNING!!
For getting the output, you need to put the javascript codeunder html tags and save it with the extension .html and open itwith 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 CHROMEBROWSER):