Você está na página 1de 12

JavaScript Tutorials: ARRAYS

Exercise 1: Creating and accessing elements of an array


<script language="javascript">
var num10 = new Array(10);
var num = [21, 0, 91, 45, 32, -13, -34, 75, 44, 11];
for (i=0; i<10; i++) {
num10[i] = 10*num[i];
}
for (i=0; i<=9; i++) {
document.write("number is " + num[i] + "<br />");
}
document.write("<br />");
for (i=0; i<10; i++) {
document.write("number by 10 is " + num10[i]+ "<br />");
}
</script>

Exercise 2: Implicit types with arrays


<script language="javascript">
var stringArray = ["aaa", "bbb", "ccc", "ddd", "eee"];
var numArray = [3, 59, 22, 31, 67];
for (i=0; i<5; i++) {
document.write("Sum is " + stringArray[i] + numArray[i] + "<br />");
} </script>

Lecturer: P Kanaksabee

Exercise 3: Using built-in function with arrays


<script language="javascript">
function roundNum(arr) {
for (i=0; i<5; i++) {
document.write("Rounded number is " + Math.round(arr[i])+ "<br />");
}
}
var numArray = [3.678, 59.21, 22.67, 31.93, 67.81];
roundNum(numArray);
</script>

Exercise 4: Assigning random values to an array


<script language="javascript">
function randomGenerator() {
var numArray = new Array(10);
for (i=0; i<10; i++) {
numArray[i] = Math.floor(Math.random()*10);
document.write("The Random number is: " + numArray[i]);
}
}
randomGenerator();
</script>

Lecturer: P Kanaksabee

Exercise 5: Defining an array and calculate sum of element squares


<script language="javascript">
numArray = new Array (2, 5, 6, -3, 0, -7, 9, 4);
sumSquares = 0;
for (i=0; i<8; i++) {
sumSquares += numArray[i]*numArray[i];
}
document.write("The sum of the squares of these " + numArray.length + "
numbers:<br />");
for (i=0; i<8; i++) {
document.write(numArray[i] + ", ");
}
document.write("is <h2>" + sumSquares + "</h2>");
</script>

Exercise 6: Defining a two-dimensional array


<script language="javascript">
arr = [[3, 9, 2], [5, 1, 7]];
document.write("Here is a 2D array (matrix)<br />");
for (i=0; i<2; i++) {
for (j=0; j<3; j++)

document.write (arr[i][j] + " ");


}
document.write("<br />");
} </script>

Lecturer: P Kanaksabee

Exercise 7: Sorting string and number arrays


<script language="javascript">
function ascendingOrder(a, b) {
num1 = parseInt(a);
num2 = parseInt(b);
return num1 - num2;
}
someStates = ["MA", "AZ", "RI", "NH"];
document.write("States sorted in ascending order:<br />" + someStates.sort());
document.write("<br />States sorted in descending order:<br />" +
someStates.sort().reverse());
document.write("<br />==============================");

someNumbers = [25, -10, 3, 0, 56, 78, 90];


document.write("<br />Numbers sorted in an ascending order<br />" +
someNumbers.sort());
document.write("<br />Numbers sorted in an descending order<br />" +
someNumbers.sort().reverse());
document.write("<br />==============================");
document.write("<br />Numbers sorted in an ascending order<br />" +
someNumbers.sort(ascendingOrder));
document.write("<br />Numbers sorted in an descending order<br />" +
someNumbers.sort(ascendingOrder).reverse());
</script>

Lecturer: P Kanaksabee

Exercise 8: Accessing multiple arrays based on a condition


<script language="javascript">
function flightInfo(got) {
for (i=0; i<6; i++) {
if (got == flightNumber[i]) break;
}
document.write("Here is your flight info:<br />");
document.write("Airline: " + airline[i] + "<br />");
document.write("Flight Number: " + flightNumber[i] + "<br />");
document.write("Terminal: " + terminal[i] + "<br />");
document.write("Gate: " + gate[i] + "<br />");
document.write("Please proceed to gate. Your flight departure time is
1/2 hr from now. Thank you for choosing our airline. Have a safe and
pleasant trip.");
}
airline = ["Lufthanza", "Swiss Air", "USAir", "Northwest Airlines", "British Airways",
"Air France"];
flightNumber = [356, 89, 1230, 952, 513, 910];
terminal = ["E", "D", "A", "C", "B", "F"];
gate = [5, 10, 3, 7, 1, 8];

input = prompt("Please, select your flight number", "356, 89, 1230, 952, 513, or
910");
flightInfo(input);
</script>

Lecturer: P Kanaksabee

Exercise 9: Creating two arrays, initializing & displaying their elements


<script type = "text/javascript">
function initializeArrays()
{
var n1 = new Array( 5 );
var n2 = new Array();
for ( var i = 0; i < n1.length; ++i )
n1[ i ] = i;
for ( i = 0; i < 5; ++i )
n2[ i ] = i;
outputArray( "Array n1 contains", n1 );
outputArray( "Array n2 contains", n2 );
}
function outputArray( header, theArray )
{
document.writeln( "<h2>" + header + "</h2>" );
document.writeln( "<table border = \"1\" width =" +
"\"100%\">" );
document.writeln( "<thead><th width = \"100\"" +
"align = \"left\">Subscript</th>" +
"<th align = \"left\">Value</th></thead><tbody>" );
for ( var i = 0; i < theArray.length; i++ )
document.writeln( "<tr><td>" + i + "</td><td>" +
theArray[ i ] + "</td></tr>" );

Lecturer: P Kanaksabee

document.writeln( "</tbody></table>" );
}
window.addEventListener( "load", initializeArrays, false );
</script>

Exercise 10: What will be the output of the following program?


<SCRIPT LANGUAGE = "JavaScript">
var a = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];
someFunction( a, 0 );
function someFunction( b, x )
{
if ( x < b.length ) {
someFunction( b, x + 1 );
document.writeln( b[ x ] + " " );
}
}
</SCRIPT>

Exercise 11: Adding updated content to a Form


<form id = "sales" action = "#">
<p>Enter sales amount:</p>
<p><input type = "text" id = "newEntry">
<input id = "submitButton" type = "button" value = "Submit">
<p><textarea id = "output" rows = "10" cols = "70"></textarea></p>
</form>

Lecturer: P Kanaksabee

Save the following as an external JavaScript file


var total = [0, 0, 0, 0, 0, 0, 0, 0, 0];
var newEntry;
var output;
function start()
{
var submitButton = document.getElementById( "submitButton" );
submitButton.addEventListener( "click", addEntry, false );
newEntry = document.getElementById( "newEntry" );
output = document.getElementById( "output" );
}
function addEntry()
{
var salary;
var x;
salary = 200 + parseInt( sales.newEntry.value ) * 0.09;
x = Math.floor ( salary / 100 );
if ( salary < 0 )
return;
else if ( x > 9 )
x = 10;
++total[ x - 2 ]
outputArray();
}
function outputArray()
{
sales.output.value =
"Number of people who earned salaries " +

Lecturer: P Kanaksabee

"in the following ranges:\n" +


"$200-$299 \t " + total[ 0 ] + "\n" +
"$300-$399 \t " + total[ 1 ] + "\n" +
"$400-$499 \t " + total[ 2 ] + "\n" +
"$500-$599 \t " + total[ 3 ] + "\n" +
"$600-$699 \t " + total[ 4 ] + "\n" +
"$700-$799 \t " + total[ 5 ] + "\n" +
"$800-$899 \t " + total[ 6 ] + "\n" +
"$900-$999 \t " + total[ 7 ] + "\n" +
"$1000 and over \t " + total[ 8 ];
}
window.addEventListener( "load", start, false );

Exercise 12: Using the split function to break an array of string into substrings.
<script type="text/javascript">
function splitString(stringToSplit, separator) {
var arrayOfStrings = stringToSplit.split(separator);
document.write('The original string is: "' + stringToSplit + '"');
document.write('The separator is: "' + separator + '"');
document.write("The array has " + arrayOfStrings.length + " elements: ");
for (var i=0; i < arrayOfStrings.length; i++)
document.write(arrayOfStrings[i] + " / ");
}
var tempestString = "Oh brave new world that has such people in it.";
var monthString = "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec";
var space = " ";
var comma = ",";
splitString(tempestString, space);
splitString(tempestString);

Lecturer: P Kanaksabee

splitString(monthString, comma);
</script>
Lab Task 1: JavaScript / DOM
Write the JavaScript code to add behavior to the following page for finding
palindromes. A palindrome is a word that is spelled the same forward as backward,
such as "madam" or "Anna". The page UI allows the user to type a phrase into a text
box. The user can click a "Find Palindromes" button to find palindrome words in that
phrase. Match case-insensitively; for example, "rotOR" is a palindrome. You may
assume that words in the phrase are separated by single spaces and contain only
letters. A one-letter word such as "I" is defined to be a palindrome.

Each palindrome found should be inserted as a bullet into a list with the id of
palindromes. Every other palindrome (the first, third, fifth, etc.) should be given a
gray background color of #CC0000. Underneath the list of palindromes you should
display text such as "5 total palindrome(s)" in the div with id of count.

The user can optionally specify a minimum and maximum word length by typing
integer values into two text boxes with id of min and max respectively. If a minimum
is specified, you should include only palindrome words that contain at least that
many letters inclusive. If a maximum is specified, you should include only palindrome
words that contain at most that many letters inclusive. If the min or max is left blank,
the length is unbounded in that direction. For example, a minimum of 3 and a blank
maximum finds all palindromes of at least 3 letters. You may assume that the text
typed in these boxes will either be blank or a valid non-negative integer, and that
max will be min.

The code should work for multiple clicks of the button. On each click it should clear
any previous found information.

Lecturer: P Kanaksabee

10

<h1> Palindrome Finder! </h1>


<div> Phrase: <input id="phrase" type="text" size="70" /> </div>
<div> Length: <input id="min" type="text" size="2" /> to
<input id="max" type="text" size="2" /> </div>
<div> <button id="find"> Find Palindromes </button> </div>
<ul id="palindromes"></ul>
<div id="count"></div>

These screenshots show the initial state, and after phrases have been typed and
"Find Palindromes" is clicked.

Lecturer: P Kanaksabee

11

Task 2:
Write a JavaScript program that prompts the user to enter the size, number of pizza
to purchase and unit price for a pizza consecutively, once the page is loaded. The
program must respond by printing the total price of purchase as per the size of pizza
selected.
Pizza Type (size)

Unit Price

Small

Rs. 50

Medium

Rs. 100

Large

Rs. 150

Task 3:
Write a JavaScript program that calculates and tabulates the squares and cubes of
the numbers from 10 to 20.
[Note: this program does not require any input from the user.]

Task 4:
Write a JavaScript program to achieve the following:
(i)

displaying the message You will be redirected to the new Web site in 5
seconds!!, in the status bar of the Web Browser, once the page load

(ii)

after five seconds, the user is automatically sent to the new URL:
http://www.cybercity.com

Task 5:
Write a JavaScript program to prompt the user for the radius of a sphere and call
function sphereVolume to calculate and display the volume of the sphere in the
status bar. Use the formula:
Volume=( 4.0 / 3.0 ) * Math.PI * Math.pow(radius, 3)
to calculate the volume. The user should input the radius through a text field and
press the button Compute to initiate the calculation.

Lecturer: P Kanaksabee

12

Você também pode gostar