JavaScript - Set 2JavaScript Tool Box (Command Set)
Math.floor = rounds a number off
Math.random() = generates random number
parseFloat() = converts string data to data type float
Math.pow = exponential values
Math.pi = value of PI
recursion vs. iteration
Arrays
passing by value vs. passing by reference
linear search vs. binary search
For/in loop structure
toUpperCase(), toLowerCase(), charAt(), charCodeAt()
Style Methods
Date methods
Random Number Generation:
<script type = "text/javascript">
<!--
var value;
document.writeln(
"<table border = \"1\" width = \"50%\">" );
document.writeln(
"<caption>Random Numbers</caption><tr>" );
//Generate a random number between 1 and 6
for ( var i = 1; i <= 20; i++ ) {
value = Math.floor( 1 + Math.random() * 6 );
document.writeln( "<td>" + value + "</td>" );
// write end and start <tr> tags when
// i is a multiple of 5 and not 20
if ( i % 5 == 0 && i != 20 )
document.writeln( "</tr><tr>" );
}
document.writeln( "</tr></table>" );
// -->
</script>
Accessing Components from a Form:
Accesses components form a form, uses onclick event handler and
random numbers.
<html>
<head>
<title>Program that Simulates the Game of Craps</title>
<script type = "text/javascript">
<!--
// variables used to test the state of the game
var WON = 0, LOST = 1, CONTINUE_ROLLING = 2;
// other variables used in program
var firstRoll = true, // true if first roll
sumOfDice = 0, // sum of the dice
myPoint = 0, // point if no win/loss on first roll
gameStatus = CONTINUE_ROLLING; // game not over yet
// process one roll of the dice
function play()
{
if ( firstRoll ) { // first roll of the dice
sumOfDice = rollDice();
switch ( sumOfDice ) {
case 7: case 11: // win on first roll
gameStatus = WON;
// clear point field
document.craps.point.value = "";
break;
case 2: case 3: case 12: // lose on first roll
gameStatus = LOST;
// clear point field
document.craps.point.value = "";
break;
default: // remember point
gameStatus = CONTINUE_ROLLING;
myPoint = sumOfDice;
document.craps.point.value = myPoint;
firstRoll = false;
}
}
else {
sumOfDice = rollDice();
if ( sumOfDice == myPoint ) // win by making point
gameStatus = WON;
else
if ( sumOfDice == 7 ) // lose by rolling 7
gameStatus = LOST;
}
if ( gameStatus == CONTINUE_ROLLING )
window.status = "Roll again";
else {
if ( gameStatus == WON )
window.status = "Player wins. " +
"Click Roll Dice to play again.";
else
window.status = "Player loses. " +
"Click Roll Dice to play again.";
firstRoll = true;
}
}
// roll the dice
function rollDice()
{
var die1, die2, workSum;
die1 = Math.floor( 1 + Math.random() * 6 );
die2 = Math.floor( 1 + Math.random() * 6 );
workSum = die1 + die2;
document.craps.firstDie.value = die1;
document.craps.secondDie.value = die2;
document.craps.sum.value = workSum;
return workSum;
}
// -->
</script>
</head>
<body>
<form name = "craps" action = "">
<table border = "1">
<caption>Craps</caption>
<tr><td>Die 1</td>
<td><input name = "firstDie" type = "text" />
</td></tr>
<tr><td>Die 2</td>
<td><input name = "secondDie" type = "text" />
</td></tr>
<tr><td>Sum</td>
<td><input name = "sum" type = "text" />
</td></tr>
<tr><td>Point</td>
<td><input name = "point" type = "text" />
</td></tr>
<tr><td><input type = "button" value = "Roll Dice"
onclick = "play()" /></td></tr>
</table>
</form>
</body>
</html>
Recursion vs. Iteration
<html>
<head>
<title>Recursive Factorial
Function</title>
<script type = "text/javascript">
<!--
document.writeln( "<h1>Factorials of 1 to 10</h1>" );
document.writeln(
"<table border = '1' width = '100%'>" );
for ( var i = 0; i <= 10; i++ )
document.writeln( "<tr><td>" + i + "!</td><td>" +
factorial( i ) + "</td></tr>" );
document.writeln( "</table>" );
// Recursive definition of function factorial
function factorial( number )
{
if ( number <= 1 ) // base case
return 1;
else
return number * factorial( number - 1 );
}
// -->
</script>
Fibonacci Series - Recursion Example:
<html>
<head>
<title>Recursive Fibonacci Function</title>
<script type = "text/javascript">
// Event handler for button XHTML component in myForm
function getFibonacciValue()
{
var value = parseInt(
document.myForm.number.value );
window.status =
"Calculating Fibonacci number for " + value;
document.myForm.result.value = fibonacci( value );
window.status = "Done calculating Fibonacci number";
}
// Recursive definition of function fibonacci
function fibonacci( n )
{
if ( n == 0 || n == 1 ) // base case
return n;
else
return fibonacci( n - 1 ) + fibonacci( n - 2 );
}
</script>
</head>
<body>
<form name = "myForm" action = "">
<table border = "1">
<tr><td>Enter an integer</td>
<td><input name = "number" type = "text" /></td>
<td><input type = "button" value = "Calculate"
onclick = "getFibonacciValue()" /></td></tr>
<tr><td>Fibonacci value</td>
<td><input name = "result" type = "text" /></td></tr>
</table>
</form>
</body>
</html>
parseFloat() and finding the MAX of 3 values:
<script type = "text/javascript">
<!--
var input1 =
window.prompt( "Enter first number", "0" );
var input2 =
window.prompt( "Enter second number", "0" );
var input3 =
window.prompt( "Enter third number", "0" );
var value1 = parseFloat( input1 );
var value2 = parseFloat( input2 );
var value3 = parseFloat( input3 );
var maxValue = maximum( value1, value2, value3 );
document.writeln( "First number: " + value1 +
"<br />Second number: " + value2 +
"<br />Third number: " + value3 +
"<br />Maximum is: " + maxValue );
// maximum method definition (called from line 25)
function maximum( x, y, z )
{
return Math.max( x, Math.max( y, z ) );
}
// -->
</script>
Scope - Global vs. Local:
<script type = "text/javascript">
<!--
var x = 1; // global variable
function start()
{
var x = 5; // variable local to function start
document.writeln( "local x in start is " + x );
functionA(); // functionA has local x
functionB(); // functionB uses global variable x
functionA(); // functionA reinitializes local x
functionB(); // global variable x retains its value
document.writeln(
"<p>local x in start is " + x + "</p>" );
}
function functionA()
{
var x = 25; // initialized each time
// functionA is called
document.writeln( "<p>local x in functionA is " +
x + " after entering functionA" );
++x;
document.writeln( "<br />local x in functionA is "
+ x + " before exiting functionA"
+ "</p>" );
}
function functionB()
{
document.writeln( "<p>global variable x is " + x +
" on entering functionB" );
x *= 10;
document.writeln( "<br />global variable x is "
+ x + " on exiting functionB"
+ "</p>" );
}
// -->
</script>
Math Functions: pi and pow:
<script type = "text/javascript">
<!--
function displayVolume()
{
var radius = parseFloat( myForm.radiusField.value );
window.status = "Volume is " + sphereVolume( radius );
}
function sphereVolume( r )
{
return ( 4.0 / 3.0 ) * Math.PI * Math.pow( r, 3 );
}
// -->
</script>
Linear Search in an Array
Must search through approximately 505 of possible values.
<html >
<head>
<title>Linear Search of an Array</title>
<script type = "text/javascript">
<!--
var a = new Array( 100 ); // create an Array
// fill Array with even integer values from 0 to 198
for ( var i = 0; i < a.length; ++i )
a[ i ] = 2 * i;
// function called when "Search" button is pressed
function buttonPressed()
{
var searchKey = searchForm.inputVal.value;
// Array a is passed to linearSearch even though it
// is a global variable. Normally an array will
// be passed to a method for searching.
var element = linearSearch( a, parseInt( searchKey ) );
if ( element != -1 )
searchForm.result.value =
"Found value in element " + element;
else
searchForm.result.value = "Value not found";
}
// Search "theArray" for the specified "key" value
function linearSearch( theArray, key )
{
for ( var n = 0; n < theArray.length; ++n )
if ( theArray[ n ] == key )
return n;
return -1;
}
// -->
</script>
</head>
<body>
<form name = "searchForm" action = "">
<p>Enter integer search key<br />
<input name = "inputVal" type = "text" />
<input name = "search" type = "button" value = "Search"
onclick = "buttonPressed()" /><br /></p>
<p>Result<br />
<input name = "result" type = "text" size = "30" /></p>
</form>
</body>
</html>
Binary Search - More Efficient than Linear Method:
Uses recursive technique to reduce search through array
elements.
Exponentially reduces possible range of values by succesively halving
each search.
<html>
<head>
<title>Linear Search of an
Array</title>
<script type = "text/javascript">
<!--
var a = new Array( 100 ); // create an Array
// fill Array with even integer values from 0 to 198
for ( var i = 0; i < a.length; ++i )
a[ i ] = 2 * i;
// function called when "Search" button is pressed
function buttonPressed()
{
var searchKey = searchForm.inputVal.value;
// Array a is passed to linearSearch even though it
// is a global variable. Normally an array will
// be passed to a method for searching.
var element = linearSearch( a, parseInt( searchKey ) );
if ( element != -1 )
searchForm.result.value =
"Found value in element " + element;
else
searchForm.result.value = "Value not found";
}
// Search "theArray" for the specified "key" value
function linearSearch( theArray, key )
{
for ( var n = 0; n < theArray.length; ++n )
if ( theArray[ n ] == key )
return n;
return -1;
}
// -->
</script>
</head>
<body>
<form name = "searchForm" action = "">
<p>Enter integer search key<br />
<input name = "inputVal" type = "text" />
<input name = "search" type = "button" value = "Search"
onclick = "buttonPressed()" /><br /></p>
<p>Result<br />
<input name = "result" type = "text" size = "30" /></p>
</form>
</body>
</html>
Sorting Array Values:
<html>
<head>
<title>Sorting an Array with Array
Method sort</title>
<script type = "text/javascript">
<!--
function start()
{
var a = [ 10, 1, 9, 2, 8, 3, 7, 4, 6, 5 ];
document.writeln( "<h1>Sorting an Array</h1>" );
outputArray( "Data items in original order: ", a );
a.sort( compareIntegers ); // sort the array
outputArray( "Data items in ascending order: ", a );
}
// outputs "header" followed by the contents of "theArray"
function outputArray( header, theArray )
{
document.writeln( "<p>" + header +
theArray.join( " " ) + "</p>" );
}
// comparison function for use with sort
function compareIntegers( value1, value2 )
{
return parseInt( value1 ) - parseInt( value2 );
}
// -->
</script>
</head><body onload = "start()"></body>
</html>
Adding Array Elements:
<html>
<head>
<title>Sum the Elements of an Array</title>
<script type = "text/javascript">
<!--
function start()
{
var theArray = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];
var total1 = 0, total2 = 0;
for ( var i = 0; i < theArray.length; i++ )
total1 += theArray[ i ];
document.writeln( "Total using subscripts: " + total1 );
for ( var element in theArray )
total2 += theArray[ element ];
document.writeln( "<br />Total using for/in: " +
total2 );
}
// -->
</script>
</head><body onload = "start()"></body>
</html>
Dice Roll, Using Arrays and Dynamically Writing HTML:
<script
language="JavaScript">
<!--
var face, frequency = [
, 0, 0, 0, 0, 0, 0 ];
// summarize results
for ( var roll = 1; roll <= 6000; ++roll ) {
face = Math.floor( 1 + Math.random() * 6 );
++frequency[ face ];
}
document.writeln( "<table border = \"1\"" +
"width = \"100%\">" );
document.writeln( "<thead><th width = \"100\"" +
" align = \"left\">Face<th align = \"left\">" +
"Frequency</th></thead></tbody>" );
for ( face = 1; face < frequency.length; ++face )
document.writeln( "<tr><td>" + face + "</td><td>" +
frequency[ face ] + "</td></tr>" );
document.writeln( "</tbody></table>" );
// -->
</script>
Adding Elements of an Array and using For/in:
<html>
<head>
<title>Sum the Elements of an Array</title>
<script type = "text/javascript">
<!--
function start()
{
var theArray = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];
var total1 = 0, total2 = 0;
for ( var i = 0; i < theArray.length; i++ )
total1 += theArray[ i ];
document.writeln( "Total using subscripts: " + total1 );
for ( var element in theArray )
total2 += theArray[ element ];
document.writeln( "<br />Total using for/in: " +
total2 );
}
// -->
</script>
</head><body onload = "start()"></body>
</html>
Dealing with Strings and Characters:
<script type = "text/javascript">
<!--
var s = "ZEBRA";
var s2 = "AbCdEfG";
document.writeln( "<p>Character at index 0 in '" +
s + "' is " + s.charAt( 0 ) );
document.writeln( "<br />Character code at index 0 in '"
+ s + "' is " + s.charCodeAt( 0 ) + "</p>" );
document.writeln( "<p>'" +
String.fromCharCode( 87, 79, 82, 68 ) +
"' contains character codes 87, 79, 82 and 68</p>" )
document.writeln( "<p>'" + s2 + "' in lowercase is '" +
s2.toLowerCase() + "'" );
document.writeln( "<br />'" + s2 + "' in uppercase is '"
+ s2.toUpperCase() + "'</p>" );
// -->
</script>
Date Object, using Date methods:
<script type = "text/javascript">
<!--
var current = new Date();
document.writeln(
"<h1>String representations and valueOf</h1>" );
document.writeln( "toString: " + current.toString() +
"<br />toLocaleString: " + current.toLocaleString() +
"<br />toUTCString: " + current.toUTCString() +
"<br />valueOf: " + current.valueOf() );
document.writeln(
"<h1>Get methods for local time zone</h1>" );
document.writeln( "getDate: " + current.getDate() +
"<br />getDay: " + current.getDay() +
"<br />getMonth: " + current.getMonth() +
"<br />getFullYear: " + current.getFullYear() +
"<br />getTime: " + current.getTime() +
"<br />getHours: " + current.getHours() +
"<br />getMinutes: " + current.getMinutes() +
"<br />getSeconds: " + current.getSeconds() +
"<br />getMilliseconds: " +
current.getMilliseconds() +
"<br />getTimezoneOffset: " +
current.getTimezoneOffset() );
document.writeln(
"<h1>Specifying arguments for a new Date</h1>" );
var anotherDate = new Date( 2001, 2, 18, 1, 5, 0, 0 );
document.writeln( "Date: " + anotherDate );
document.writeln(
"<h1>Set methods for local time zone</h1>" );
anotherDate.setDate( 31 );
anotherDate.setMonth( 11 );
anotherDate.setFullYear( 2001 );
anotherDate.setHours( 23 );
anotherDate.setMinutes( 59 );
anotherDate.setSeconds( 59 );
document.writeln( "Modified date: " + anotherDate );
// -->
</script>
JavaScript Style and Markup Functions
<script type = "text/javascript">
<!--
var anchorText = "This is an anchor",
blinkText = "This is blinking text",
fixedText = "This is monospaced text",
linkText = "Click here to go to anchorText",
strikeText = "This is strike out text",
subText = "subscript",
supText = "superscript";
document.writeln( anchorText.anchor( "top" ) );
document.writeln( "<br />" + blinkText.blink() );
document.writeln( "<br />" + fixedText.fixed() );
document.writeln( "<br />" + strikeText.strike() );
document.writeln(
"<br />This is text with a " + subText.sub() );
document.writeln(
"<br />This is text with a " + supText.sup() );
document.writeln(
"<br />" + linkText.link( "#top" ) );
// -->
</script>
String Searching:
<html>>
<head>
<title>
Searching Strings with indexOf and lastIndexOf
</title>
<script type = "text/javascript">
<!--
var letters = "abcdefghijklmnopqrstuvwxyzabcdefghijklm";
function buttonPressed()
{
searchForm.first.value =
letters.indexOf( searchForm.inputVal.value );
searchForm.last.value =
letters.lastIndexOf( searchForm.inputVal.value );
searchForm.first12.value =
letters.indexOf( searchForm.inputVal.value, 12 );
searchForm.last12.value =
letters.lastIndexOf(searchForm.inputVal.value, 12 );
}
// -->
</script>
</head>
<body>
<form name = "searchForm" action = "">
<h1>The string to search is:<br />
abcdefghijklmnopqrstuvwxyzabcdefghijklm</h1>
<p>Enter substring to search for
<input name = "inputVal" type = "text" />
<input name = "search" type = "button" value = "Search"
onclick = "buttonPressed()" /><br /></p>
<p>First occurrence located at index
<input name = "first" type = "text" size = "5" />
<br />Last occurrence located at index
<input name = "last" type = "text" size = "5" />
<br />First occurrence from index 12 located at index
<input name = "first12" type = "text" size = "5" />
<br />Last occurrence from index 12 located at index
<input name = "last12" type = "text" size = "5" /></p>
</form>
</body>
</html>
Splitting Strings and Substrings:
<html>
<head>
<title>String Method split and substring</title>
<script type = "text/javascript">
<!--
function splitButtonPressed()
{
var strings = myForm.inputVal.value.split( " " );
myForm.output.value = strings.join( "\n" );
myForm.outputSubstring.value =
myForm.inputVal.value.substring( 0, 10 );
}
// -->
</script>
</head>
<body>
<form name = "myForm" action = "">
<p>Enter a sentence to split into words<br />
<input name = "inputVal" type = "text" size = "40" />
<input name = "splitButton" type = "button" value =
"Split" onclick = "splitButtonPressed()" /></p>
<p>The sentence split into words is<br />
<textarea name = "output" rows = "8" cols = "34">
</textarea></p>
<p>The first 10 characters of the input string are
<input name = "outputSubstring" type = "text"
size = "15" /></p>
</form>
</body>
|