Working with Arrays - Exercise

Contact Us or call 1-877-932-8228
Working with Arrays - Exercise

Working with Arrays

Duration: 15 to 25 minutes.

In this exercise, you will practice working with arrays.

  1. Open VariablesArraysOperators/Exercises/Arrays.html for editing.
  2. Below the comment, declare a rockStars array and populate it with four values entered by the user.
  3. Add functionality to the buttons, so that alerts pop up with values from the array when the buttons are clicked.
  4. Test your solution in a browser.

Code Sample:

VariablesArraysOperators/Exercises/Arrays.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>JavaScript Arrays</title>
<link href="style.css" rel="stylesheet" type="text/css">
<script type="text/javascript">
	/*
		Declare a rockStars array and populate it with 
		four values entered by the user.
	*/
</script>
</head>
<body>
<form>
	<input type="button" value="Favorite">
	<input type="button" value="Next Favorite">
	<input type="button" value="Next Favorite">
	<input type="button" value="Next Favorite">
</form>
</body>
</html>

Solution:

VariablesArraysOperators/Solutions/Arrays.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>JavaScript Arrays</title>
<link href="style.css" rel="stylesheet" type="text/css">
<script type="text/javascript">
	var rockStars = new Array();
	rockStars[0] = window.prompt("Who is your favorite rock star?", "");
	rockStars[1] = window.prompt("And your next favorite rock star?", "");
	rockStars[2] = window.prompt("And your next favorite rock star?", "");
	rockStars[3] = window.prompt("And your next favorite rock star?", "");
</script>
</head>
<body>
<form>
	<input type="button" value="Favorite" onclick="alert(rockStars[0]);">
	<input type="button" value="Next Favorite" onclick="alert(rockStars[1]);">
	<input type="button" value="Next Favorite" onclick="alert(rockStars[2]);">
	<input type="button" value="Next Favorite" onclick="alert(rockStars[3]);">
</form>
</body>
</html>
Next