JavaScript DHTML/Language Basics/Array
Содержание
- 1 Adding a prototype Property
- 2 <SCRIPT LANGUAGE="JavaScript"> document.write("Array a is brought to you by: " + a.sponsor + "") document.write("Array b is brought to you by: " + b.sponsor + "<P>") document.write("Array c is brought to you by: " + c.sponsor + "<P>") document.write("Array d is brought to you by: " + d.sponsor + "<P>") </SCRIPT> </H2> </BODY> </HTML> </source> A Looping Array Lookup
- 3 Parallel Array Lookup II
- 4 Arrays within Arrays
- 4.1 Array - concat and slice
- 4.2 Array Concatenation
- 4.3 Array definition and iteration
- 4.4 Array loop, find:Control array : Two dimension array
- 4.5 Array - properties and methods:length, join, reverse, push,pop,shift
- 4.6 Array.reverse() Method
- 4.7 Array - sort()
- 4.8 Array.sort() Possibilities
- 4.9 Array - splice
- 4.10 Array Utility functions
- 4.11 Array with a numeric parameter and assign data to it
- 4.12 A Simple Parallel Array Lookup
- 5 Parallel Array Lookup
- 6 <SCRIPT> var theArray = new Array("a","N","Mo","T", "Mr. Smith", "N", "n", "A",2); document.write ("Original array: " + theArray); document.write (""); theArray.sort(); document.write ("Default Sorted array: " + theArray); document.write (""); theArray.sort(function(x,y){ var a = String(x).toUpperCase(); var b = String(y).toUpperCase(); if (a > b) return 1 if (a < b) return -1 return 0; }); document.write ("Custom sorted array: " + theArray); </SCRIPT>
- 7 <SCRIPT> function numSort(a,b){ return a - b; } var numArray = new Array (59, 4, 63, 12, 17, 3, 2 , 1) document.write ("Original array: " + numArray); document.write (""); document.write ("Default Sorted array: " + numArray.sort()); document.write (""); document.write ("Numerically sorted array: " + numArray.sort(numSort)); </SCRIPT>
- 8 Extending Arrays
- 9 <SCRIPT> var myArray = new Array(4); myArray[0] = "A"; myArray[1] = "c"; myArray[2] = "s"; myArray[3] = "d"; var i = 3; var theYear = myArray[i]; document.write("It is the year of the " + theYear + "."); </SCRIPT>
- 10 <SCRIPT> var theArray = new Array("N","M","T","M"); document.write ("Original array: " + theArray); document.write (""); theArray.reverse(); document.write ("Reversed array: " + theArray); document.write (""); theArray.sort(); document.write ("Sorted array: " + theArray); document.write (""); document.write("Concatenated: " + theArray.concat("Cypher", "Mouse")); </SCRIPT>
- 11 Simple Array Demo
- 12 <SCRIPT> var x = makeArray(); document.write(showArray(x)); </SCRIPT>
- 13 Using Arrays
- 14 Using Arrays
Adding a prototype Property
<source lang="html4strict">
<HTML> <HEAD> <TITLE>Array prototypes</TITLE> <SCRIPT LANGUAGE="JavaScript1.1"> // add prototype to all Array objects Array.prototype.sponsor = "DG" a = new Array(5) b = new Array(5) c = new Array(5) // override prototype property for one "instance" c.sponsor = "JS" // this one picks up the original prototype d = new Array(5) </SCRIPT>
<BODY><SCRIPT LANGUAGE="JavaScript">
document.write("Array a is brought to you by: " + a.sponsor + "")
document.write("Array b is brought to you by: " + b.sponsor + "<P>")
document.write("Array c is brought to you by: " + c.sponsor + "<P>")
document.write("Array d is brought to you by: " + d.sponsor + "<P>")
</SCRIPT>
</H2>
</BODY>
</HTML>
</source>
A Looping Array Lookup
<source lang="html4strict">
/* JavaScript Bible, Fourth Edition by Danny Goodman John Wiley & Sons CopyRight 2001
- /
<HTML> <HEAD> <TITLE>Parallel Array Lookup II</TITLE> <SCRIPT LANGUAGE="JavaScript"> // the data var regionalOffices = new Array("New York", "Chicago", "Houston", "Portland") var regionalManagers = new Array("Shirley Smith", "Todd Gaston", "Leslie Jones", "Harold Zoot") var regOfficeQuotas = new Array(300000, 250000, 350000, 225000) // do the lookup into parallel arrays function getData(form) {
// make a copy of the text box contents var inputText = form.officeInp.value // loop through all entries of regionalOffices array for (var i = 0; i < regionalOffices.length; i++) { // compare uppercase versions of entered text against one entry // of regionalOffices if (inputText.toUpperCase() == regionalOffices[i].toUpperCase()) { // if they"re the same, then break out of the for loop break } } // make sure the i counter hasn"t exceeded the max index value if (i < regionalOffices.length) { // display corresponding entries from parallel arrays form.manager.value = regionalManagers[i] form.quota.value = regOfficeQuotas[i] } else { // loop went all the way with no matches // empty any previous values form.manager.value = "" form.quota.value = "" // advise user alert("No match found for " + inputText + ".") }
} </SCRIPT> </HEAD> <BODY>
Parallel Array Lookup II
<FORM NAME="officeData"> <P> Enter a regional office: <INPUT TYPE="text" NAME="officeInp" SIZE=35> <INPUT TYPE="button" VALUE="Search" onClick="getData(this.form)">
The manager is:
<INPUT TYPE="text" NAME="manager" SIZE=35>
The office quota is:
<INPUT TYPE="text" NAME="quota" SIZE=8>
</FORM> </BODY> </HTML>
</source>
An Array within an Array
<source lang="html4strict">
<HTML> <HEAD> <TITLE>Arrays within Arrays</TITLE> </HEAD> <BODY>
Arrays within Arrays
<SCRIPT LANGUAGE="JavaScript"></SCRIPT> </BODY> </HTML>
</source>
Array - concat and slice
<source lang="html4strict">
<html>
<body>
<script type="text/javascript">
var nameArray = new Array(3)
nameArray[0] = "Joe"
nameArray[1] = "Dan"
nameArray[2] = "Darlene"
var nameArray2 = new Array(3)
nameArray2[0] = "Lee"
nameArray2[1] = "Zong"
nameArray2[2] = "JJ"
var nameArray3 = new Array("Firat","Basdr")
document.write(nameArray.join() + "
")
document.write(nameArray.concat(nameArray2) + "
")
document.write(nameArray.concat(nameArray2,nameArray3) + "
")
document.write(nameArray.slice(1) + "
")
</script>
</body>
</html>
</source>
Array Concatenation
<source lang="html4strict">
<HTML> <HEAD> <TITLE>Array Concatenation</TITLE> <SCRIPT LANGUAGE="JavaScript1.1"> var arrayOne, arrayTwo, arrayThree, textObj function initialize() {
var form = document.forms[0] textObj = form.original arrayOne = new Array("A", "B","C") arrayTwo = new Array("D", "E",textObj) arrayThree = arrayOne.concat(arrayTwo) update1(form) update2(form) showArrays()
} function showArrays() {
var form = document.forms[0] form.array1.value = arrayOne.join("\n") form.array2.value = arrayTwo.join("\n") form.array3.value = arrayThree.join("\n")
} function update1(form) {
arrayThree[0] = form.source1.value form.result1.value = arrayOne[0] form.result2.value = arrayThree[0] showArrays()
} function update2(form) {
arrayThree[5].value = form.source2.value form.result3.value = arrayTwo[2].value form.result4.value = arrayThree[5].value showArrays()
} </SCRIPT> </HEAD> <BODY onLoad="initialize()"> <FORM>
arrayOne | arrayTwo | arrayThree |
---|---|---|
<TEXTAREA NAME="array1" COLS=25 ROWS=6></TEXTAREA> | <TEXTAREA NAME="array2" COLS=25 ROWS=6></TEXTAREA> | <TEXTAREA NAME="array3" COLS=25 ROWS=6></TEXTAREA> |
Enter new value for arrayThree[0]:
<INPUT TYPE="text" NAME="source1" VALUE="X">
<INPUT TYPE="button" VALUE="Change arrayThree[0]" onClick="update1(this.form)">
Current arrayOne[0] is:<INPUT TYPE="text" NAME="result1">
Current arrayThree[0] is:<INPUT TYPE="text" NAME="result2">
textObj assigned to arrayTwo[2]:
<INPUT TYPE="text" NAME="original" onFocus="this.blur()"></BR>
Enter new value for arrayThree[5]:
<INPUT TYPE="text" NAME="source2" VALUE="Y">
<INPUT TYPE="button" VALUE="Change arrayThree[5].value" onClick="update2(this.form)">
Current arrayTwo[2].value is:<INPUT TYPE="text" NAME="result3">
<INPUT TYPE="button" VALUE="Reset" onClick="location.reload()"> </FORM> </BODY> </HTML> </source>
Array definition and iteration
<source lang="html4strict">
<HTML> <HEAD> <SCRIPT language="JavaScript">
</SCRIPT> </HEAD> <BODY> <H2>Computer Parts Needed:</H2> <SCRIPT language="JavaScript">
</SCRIPT> </BODY> </HTML>
</source>
Array loop, find:Control array : Two dimension array
<source lang="html4strict">
var myArray = ["Alice", "Fred", "Jean", "Steve"]; for (var i = 0; i < myArray.length ; i++) {
alert("Item " + i + " is:" + myArray[i] + ".");
}
var nameList = ["Alice", "Fred", "Jean", "Steve"]; var ageList = [23, 32, 28, 24]; function ageLookup(name) {
for (var i = 0; i < nameList.length ; i++) { if (nameList[i] == name) { return ageList[i]; } return "Could not find " + name + ".";
}
function clearTextBoxes() {
var allInputs = document.getElementsByTagName("input"); for (var i = 0; i < allInputs.length; i++) { if (allInputs[i].type == "text") { allInputs[i].value = ""; } }
}
var salesArray = [[2300, 3105, 2909, 4800],
[1800, 1940, 2470, 4350], [900, 1200, 1923, 3810]];
var total = 0; for (var i = 0; i < salesArray.length; i++) {
for (var j = 0; j < salesArray[i].length; j++) { total += salesArray[i][j]; }
}
</source>
Array - properties and methods:length, join, reverse, push,pop,shift
<source lang="html4strict">
<html>
<body>
<script type="text/javascript">
var nameArray = new Array(3)
nameArray[0] = "Name 1"
nameArray[1] = "Name 2"
nameArray[2] = "Name 3"
document.write(nameArray.length + "
")
document.write(nameArray.join(".") + "
")
document.write(nameArray.reverse() + "
")
document.write(nameArray.push("Ola","Jon") + "
")
document.write(nameArray.pop() + "
")
document.write(nameArray.shift() + "
")
</script>
</body>
</html>
</source>
Array.reverse() Method
<source lang="html4strict">
<HTML> <HEAD> <TITLE>Array.reverse()</TITLE> <SCRIPT LANGUAGE="JavaScript1.1"> solarSys = new Array(9) solarSys[0] = "M" solarSys[1] = "V" solarSys[2] = "E" solarSys[3] = "M" solarSys[4] = "J" solarSys[5] = "S" solarSys[6] = "U" solarSys[7] = "N" solarSys[8] = "P"
function showAsIs(form) {
var delimiter = form.delim.value form.output.value = unescape(solarSys.join(delimiter))
}
function reverseIt(form) {
var delimiter = form.delim.value solarSys.reverse() form.output.value = unescape(solarSys.join(delimiter))
} </SCRIPT> <BODY> <H2>Reversing array element order</H2> <FORM> Enter a string to act as a delimiter between entries: <INPUT TYPE="text" NAME="delim" VALUE="," SIZE=5><P> <INPUT TYPE="button" VALUE="Array as-is" onClick="showAsIs(this.form)"> <INPUT TYPE="button" VALUE="Reverse the array" onClick="reverseIt(this.form)"> <INPUT TYPE="reset"> <INPUT TYPE="button" VALUE="Reload" onClick="self.location.reload()"> <TEXTAREA NAME="output" ROWS=4 COLS=60> </TEXTAREA> </FORM> </BODY> </HTML>
</source>
Array - sort()
<source lang="html4strict">
<html> <body> <script type="text/javascript"> array1=new Array("Red","Blue","Green") array2=new Array("73","19","830") array3=new Array(510,130,23,3400) array4=new Array("72","83","850",3,1,5,40) function compareNum(a,b){
return a-b
}
document.write("Sorted: " + array1.sort())
document.write("
")
document.write("Sorted without compareNum: " + array2.sort())
document.write("
")
document.write("Sorted with compareNum: " + array2.sort(compareNum))
document.write("
")
document.write("Sorted without compareNum: " + array3.sort())
document.write("
")
document.write("Sorted with compareNum: " + array3.sort(compareNum))
document.write("
")
document.write("Sorted without compareNum: " + array4.sort())
document.write("
")
document.write("Sorted with compareNum: " + array4.sort(compareNum))
</script>
</body>
</html>
</source>
Array.sort() Possibilities
<source lang="html4strict">
<HTML> <HEAD> <TITLE>Array.sort()</TITLE> <SCRIPT LANGUAGE="JavaScript1.1"> solarSys = new Array(9) solarSys[0] = "M" solarSys[1] = "V" solarSys[2] = "E" solarSys[3] = "M" solarSys[4] = "J" solarSys[5] = "S" solarSys[6] = "U" solarSys[7] = "N" solarSys[8] = "P" // comparison functions function compare1(a,b) {
// reverse alphabetical order if (a > b) {return -1} if (b > a) {return 1} return 0
} function compare2(a,b) {
// last character of planet names var aComp = a.charAt(a.length - 1) var bComp = b.charAt(b.length - 1) if (aComp < bComp) {return -1} if (aComp > bComp) {return 1} return 0
} function compare3(a,b) {
return a.length - b.length
}
function sortIt(form, compFunc) {
var delimiter = ";" if (compFunc == null) { solarSys.sort() } else { solarSys.sort(compFunc) } form.output.value = unescape(solarSys.join(delimiter))
} </SCRIPT> <BODY onLoad="document.forms[0].output.value = unescape(solarSys.join(";"))"> <H2>Sorting array elements</H2>
This document contains an array of planets in our solar system.<FORM> Click on a button to sort the array:<P> <INPUT TYPE="button" VALUE="Alphabetical A-Z" onClick="sortIt(this.form)"> <INPUT TYPE="button" VALUE="Alphabetical Z-A" onClick="sortIt(this.form,compare1)"> <INPUT TYPE="button" VALUE="Last Character" onClick="sortIt(this.form,compare2)"> <INPUT TYPE="button" VALUE="Name Length" onClick="sortIt(this.form,compare3)"> <INPUT TYPE="button" VALUE="Reload Original" onClick="self.location.reload()"> <INPUT TYPE="text" NAME="output" SIZE=62> </TEXTAREA> </FORM> </BODY> </HTML>
</source>
Array - splice
<source lang="html4strict">
<html>
<body>
<script type="text/javascript">
myCars=["BMW","Volvo","Xiali","Jili"]
document.write("myCars: " + myCars)
document.write("
")
removed=myCars.splice(2,0,"Volkswagen")
document.write("After adding 1: " + myCars)
document.write("
")
removed=myCars.splice(3,1)
document.write("After removing 1: " + myCars)
document.write("
")
removed=myCars.splice(2,1,"Seat")
document.write("After replacing 1: " + myCars)
document.write("
")
removed=myCars.splice(0,2,"Peugeot","Honda","Toyota")
document.write("After replacing 2 and adding 1: " + myCars)
</script>
</body>
</html>
</source>
Array Utility functions
<source lang="html4strict">
/* JavaScript Application Cookbook By Jerry Bradenbaugh Publisher: O"Reilly Series: Cookbooks ISBN: 1-56592-577-7
- /
<HTML> <HEAD> <TITLE>arrays.js Example</TITLE> <SCRIPT LANGUAGE="JavaScript1.2"> // arrays.js // Add up the values of all the elements, then // divide that sum by the number of elements function avg(arrObj) {
var sum = 0; for (var i = 0; i < arrObj.length; i++) { sum += arrObj[i]; } return (sum / i); }
// Iterate through the elements, // and return the highest function high(arrObj) {
var highest = arrObj[0]; for (var i = 1; i < arrObj.length; i++) { highest = (arrObj[i] > highest ? arrObj[i] : highest); } return (highest); }
// Iterate through the elements, // and return the lowest function low(arrObj) {
var lowest = arrObj[0]; for (var i = 1; i < arrObj.length; i++) { lowest = (arrObj[i] < lowest ? arrObj[i] : lowest); } return (lowest); }
// Iterate through the elements, amd perform // a string replacement on each function jsGrep(arrObj, regexp, subStr) {
for (var i = 0; i < arrObj.length; i++) { arrObj[i] = arrObj[i].replace(regexp, subStr); } return arrObj; }
// This function returns a copy of an array object // with the last element removed function truncate(arrObj) {
arrObj.length = arrObj.length - 1; return arrObj; }
// This function returns a copy of an array // object with the first element removed function shrink(arrObj) {
var tempArray = new Array(); for(var p = 1; p < arrObj.length; p++) { tempArray[p - 1] = arrObj[p]; } return tempArray; }
// This function returns a copy of an array // object with the elements of another array // object added beginning from a specified index. function integrate(arrObj, elemArray, startIndex) {
startIndex = (parseInt(Math.abs(startIndex)) < arrObj.length ? parseInt(Math.abs(startIndex)) : arrObj.length); var tempArray = new Array(); for( var p = 0; p < startIndex; p++) { tempArray[p] = arrObj[p]; } for( var q = startIndex; q < startIndex + elemArray.length; q++) { tempArray[q] = elemArray[q - startIndex]; } for( var r = startIndex + elemArray.length; r < (arrObj.length + elemArray.length); r++) { tempArray[r] = arrObj[r - elemArray.length]; } return tempArray; }
// This function returns an array reordered according to a multiple // passed in by the user. The defualt is 1. function reorganize(formObj, stepUp) {
stepUp = (Math.abs(parseInt(stepUp)) > 0 ? Math.abs(parseInt(stepUp)) : 1); var nextRound = 1; var idx = 0; var tempArray = new Array(); for (var i = 0; i < formObj.length; i++) { tempArray[i] = formObj[idx]; if (idx + stepUp >= formObj.length) { idx = nextRound; nextRound++; } else { idx += stepUp; } } return tempArray; }
</SCRIPT> </HEAD> <BODY> <SCRIPT LANGUAGE="JavaScript1.2">
</SCRIPT>
</BODY> </HTML>
</source>
Array with a numeric parameter and assign data to it
<source lang="html4strict">
<html> <body> <script type="text/javascript"> var nameArray = new Array(6) nameArray[0] = "1 item" nameArray[1] = "2 item" nameArray[2] = "3 item" nameArray[3] = "4 item" nameArray[4] = "5 item" nameArray[5] = "6 item" for (i=0; i<6; i++){
document.write(nameArray[i] + "
")
} </script> </body> </html>
</source>
A Simple Parallel Array Lookup
<source lang="html4strict">
/* JavaScript Bible, Fourth Edition by Danny Goodman John Wiley & Sons CopyRight 2001
- /
<HTML> <HEAD> <TITLE>Parallel Array Lookup</TITLE> <SCRIPT LANGUAGE="JavaScript"> // the data var regionalOffices = new Array("New York", "Chicago", "Houston", "Portland") var regionalManagers = new Array("Shirley Smith", "Todd Gaston", "Leslie Jones", "Harold Zoot") var regOfficeQuotas = new Array(300000, 250000, 350000, 225000) // do the lookup into parallel arrays function getData(form) {
var i = form.offices.selectedIndex form.manager.value = regionalManagers[i] form.quota.value = regOfficeQuotas[i]
} </SCRIPT> </HEAD> <BODY onLoad="getData(document.officeData)">
Parallel Array Lookup
<FORM NAME="officeData"> <P> Select a regional office: <SELECT NAME="offices" onChange="getData(this.form)">
<OPTION>New York <OPTION>Chicago <OPTION>Houston <OPTION>Portland
</SELECT>
The manager is:
<INPUT TYPE="text" NAME="manager" SIZE=35>
The office quota is:
<INPUT TYPE="text" NAME="quota" SIZE=8>
</FORM> </BODY> </HTML>
</source>
Assing array value inside function
<source lang="html4strict">
<html> <head> <script language="JavaScript">
</script> </head> </html>
</source>
A string array
<source lang="html4strict">
<html> <body> <script type="text/javascript"> var nameArray = new Array("Name 1","Name 2","Name 3","Name 4","Name 5","Name 6") for (i=0; i<nameArray.length; i++){
document.write(nameArray[i] + "
")
} </script> </body> </html>
</source>
A string array variable
<source lang="html4strict">
<html> <head>
<title>Concat</title> <script type = "text/javascript"> var aObject = ["A", "B", "C", "D"]; for (var i = 0; i < aObject.length; i++) { document.write(aObject[i]); } </script>
</head> <body> </body> </html>
</source>
Case-Insensitive Comparison for the Array.Sort Method
<source lang="html4strict">
<HTML> <HEAD> <TITLE> Case-insensitive comparison </TITLE> <HEAD> <BODY>
<SCRIPT>
var theArray = new Array("a","N","Mo","T", "Mr. Smith", "N", "n", "A",2);
document.write ("Original array: " + theArray);
document.write ("
");
theArray.sort();
document.write ("Default Sorted array: " + theArray);
document.write ("
");
theArray.sort(function(x,y){
var a = String(x).toUpperCase();
var b = String(y).toUpperCase();
if (a > b)
return 1
if (a < b)
return -1
return 0;
});
document.write ("Custom sorted array: " + theArray);
</SCRIPT>
</BODY> </HTML>
</source>
Custom Numeric Comparison for the Array.Sort Method
<source lang="html4strict">
<HTML> <HEAD> <TITLE> Numeric comparisons </TITLE> <HEAD> <BODY>
<SCRIPT>
function numSort(a,b){
return a - b;
}
var numArray = new Array (59, 4, 63, 12, 17, 3, 2 , 1)
document.write ("Original array: " + numArray);
document.write ("
");
document.write ("Default Sorted array: " + numArray.sort());
document.write ("
");
document.write ("Numerically sorted array: " +
numArray.sort(numSort));
</SCRIPT>
</BODY> </HTML>
</source>
Demo all methods in Array
<source lang="html4strict">
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head> <title>jsPro - Array</title> <script type="text/javascript">
/**
* +-------------------------------------------------------------------------+ * | jsPro - Error | * +-------------------------------------------------------------------------+ * | Copyright (C) 2001-2003 Stuart Wigley | * +-------------------------------------------------------------------------+ * | This library is free software; you can redistribute it and/or modify it | * | under the terms of the GNU Lesser General Public License as published by| * | the Free Software Foundation; either version 2.1 of the License, or (at | * | your option) any later version. | * | | * | This library is distributed in the hope that it will be useful, but | * | WITHOUT ANY WARRANTY; without even the implied warranty of | * | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser | * | General Public License for more details. | * | | * | You should have received a copy of the GNU Lesser General Public License| * | along with this library; if not, write to the Free Software Foundation, | * | Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA | * +-------------------------------------------------------------------------+ * | Authors: Stuart Wigley <stuartwigley@yahoo.co.uk> | * | Randolph Fielding <gator4life@cinci.rr.ru> | * +-------------------------------------------------------------------------+ * $Id: error.js,v 1.15 2003/09/22 04:41:10 gator4life Exp $ */
/**
* Property used in Error.handleError
to specify how errors are
* reported. Permissable values are:
*
* 0 No errors are reported.
* 1 Report the error name and error message using the status bar of the
* active browser window.
* 2 Report the error name and error message using an alert box.
* 3 Report the error name, error message and debug message using an alert
* box.
* 4 Report the error name, error message and debug message using a debug
* window. An instance of the Debug() class must be available.
*/
Error.prototype.debugLevel = 4;
/**
* UsesError.debugLevel
to control how errors are reported. If *Error.debugLevel
is set to 4, you must substitute the name of * yourDebug()
instance foroDebug
in the line *var jsProDebugWindow = oDebug
. * * @summary handles thrown exceptions * @author Stuart Wigley * @author Randolph Fielding * @version 1.2, 09/03/03 * @interfaceError.handleError()
* @requiresDebug.print(vMixedValue, sMessageType)
* @seeDebug()
* @seeDebug.print()
*/
Error.prototype.handleError = function() {
var sDebugMessage = this.debug; var sErrorMessage = (sDebugMessage) ? sDebugMessage : ""; switch (this.debugLevel) { case 0 : break; case 1 : window.status = this.name + ": " + this.message; break; case 2 : window.alert(this.name + "\n\n" + this.message); break; case 3 : window.alert(this.name + "\n\n" + this.message + "\n\n" + sErrorMessage); break; case 4 : var jsProDebugWindow = oDebug; if (jsProDebugWindow) { var oDebugWindow = jsProDebugWindow.debugWindow; if (oDebugWindow && !oDebugWindow.closed) { jsProDebugWindow.print(this.name + " " + this.message + " " + sErrorMessage, 1); } } }
}
/**
* Creates an object that is a subclass of Error for handling
* ArrayIndexOutOfBounds exceptions.
*
* @author Stuart Wigley
* @author Randolph Fielding
* @version 1.1, 06/27/03
* @interface new ArrayIndexOutOfBoundsException(sMethodName,
* iIndex, iArrayLength)
* @param sMethodName the name of the method where the exception was thrown
* @param iIndex the index of a hypothetical array member attempting to
* be accessed
* @param iArrayLength the length of the array
*/
function ArrayIndexOutOfBoundsException(sMethodName, iIndex, iArrayLength) {
this.name = "ArrayIndexOutOfBoundsException"; this.message = sMethodName + " has been accessed with an illegal index that is either negative or greater than the size of the array."; this.debug = "Attempting to access index " + iIndex.toString() + ", but array has an index range of 0 to " + (iArrayLength - 1).toString() + ".";
} ArrayIndexOutOfBoundsException.prototype = new Error();
/**
* Creates an object that is a subclass of Error for handling IllegalArgument
* exceptions.
*
* @author Stuart Wigley
* @author Randolph Fielding
* @version 1.2, 07/24/03
* @interface new IllegalArgumentException(sMethodName,
* vExpectedArgs, iActualArgs)
* @param sMethodName the name of the method where the exception was thrown
* @param vExpectedArgs the number of arguments expected
* @param iActualArgs the number of arguments received
*/
function IllegalArgumentException(sMethodName, vExpectedArgs, iActualArgs) {
this.name = "IllegalArgumentException"; this.message = sMethodName + " has been passed an illegal number of arguments."; this.debug = "Expected " + vExpectedArgs.toString() + " argument(s), but received " + iActualArgs.toString() + " argument(s).";
} IllegalArgumentException.prototype = new Error();
/**
* Creates an object that is a subclass of Error for handling IllegalValue
* exceptions.
*
* @author Randolph Fielding
* @version 1.0, 09/22/03
* @interface new IllegalValueException(sMethodName,
* sVariableName, vExpectedVal, vActualVal)
* @param sMethodName the name of the method where the exception was thrown
* @param sVariableName the name of the variable containing the illegal value
* @param vExpectedVal the value expected in the variable containing the
* illegal value
* @param vActualVal the value currently in the variable containing the
* illegal value
*/
function IllegalValueException(sMethodName, sVariableName, vExpectedVal, vActualVal) {
this.name = "IllegalValueException"; this.message = sMethodName + " has encountered an illegal value in variable " + sVariableName + "." this.debug = "Expected a value of " + vExpectedVal.toString() + ", but contains a value of " + vActualVal.toString() + "."
} IllegalValueException.prototype = new Error();
/**
* Creates an object that is a subclass of Error for handling
* MethodNotAvailable exceptions.
*
* @author Stuart Wigley
* @author Randolph Fielding
* @version 1.1, 06/27/03
* @interface new MethodNotAvailableException(sMethodName,
* sMethodNameNA)
* @param sMethodName the name of the method where the exception was thrown
* @param sMethodNameNA the name of the method that was not available
*/
function MethodNotAvailableException(sMethodName, sMethodNameNA) {
this.name = "MethodNotAvailableException"; this.message = "A method has been called that is not available."; this.debug = sMethodName + " attempted to call " + sMethodNameNA + ".";
} MethodNotAvailableException.prototype = new Error();
/**
* Creates an object that is a subclass of Error for handling
* PropertyNotAvailable exceptions.
*
* @author Randolph Fielding
* @version 1.1, 08/01/03
* @interface new PropertyNotAvailableException(sMethodName,
* sPropNameNA)
* @param sMethodName the name of the method where the exception was thrown
* @param sPropNameNA the name of the property that was not available
*/
function PropertyNotAvailableException(sMethodName, sPropNameNA) {
this.name = "PropertyNotAvailableException"; this.message = "A property has been accessed that is not available."; this.debug = sMethodName + " attempted to access " + sPropNameNA + ".";
} PropertyNotAvailableException.prototype = new Error();
/**
* Creates an object that is a subclass of Error for handling TypeMismatch
* exceptions.
*
* @author Stuart Wigley
* @author Randolph Fielding
* @version 1.2, 07/24/03
* @interface new TypeMismatchException(sMethodName,
* sExpectedType, sActualType)
* @param sMethodName the name of the method where the exception was thrown
* @param sExpectedType the name of the expected type of an argument
* @param sActualType the name of the actual type of an argument
*/
function TypeMismatchException(sMethodName, sExpectedType, sActualType) {
this.name = "TypeMismatchException"; this.message = sMethodName + " has been passed an argument with an illegal or inappropriate type."; this.debug = "Expected an argument with a type of " + sExpectedType + ", but received an argument with a type of " + sActualType + ".";
} TypeMismatchException.prototype = new Error();
/**
* Creates an object that is a subclass of Error for handling Unknown
* exceptions.
*
* @author Stuart Wigley
* @author Randolph Fielding
* @version 1.1, 06/27/03
* @interface new UnknownException(sMethodName)
* @param sMethodName the name of the method where the exception was thrown
*/
function UnknownException(sMethodName) {
this.name = "UnknownException"; this.message = "An unknown error has occurred in " + sMethodName + ".";
} UnknownException.prototype = new Error();
</script> <script type="text/javascript">
/**
* +-------------------------------------------------------------------------+ * | jsPro - Debug | * +-------------------------------------------------------------------------+ * | Copyright (C) 2001-2003 Stuart Wigley | * +-------------------------------------------------------------------------+ * | This library is free software; you can redistribute it and/or modify it | * | under the terms of the GNU Lesser General Public License as published by| * | the Free Software Foundation; either version 2.1 of the License, or (at | * | your option) any later version. | * | | * | This library is distributed in the hope that it will be useful, but | * | WITHOUT ANY WARRANTY; without even the implied warranty of | * | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser | * | General Public License for more details. | * | | * | You should have received a copy of the GNU Lesser General Public License| * | along with this library; if not, write to the Free Software Foundation, | * | Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA | * +-------------------------------------------------------------------------+ * | Authors: Stuart Wigley <stuartwigley@yahoo.co.uk> | * | Randolph Fielding <gator4life@cinci.rr.ru> | * +-------------------------------------------------------------------------+ * $Id: debug.js,v 1.6 2003/09/22 05:07:41 gator4life Exp $ */
/**
* Creates an object that opens a window for debugging.
*
* @author Stuart Wigley
* @author Randolph Fielding
* @version 1.1, 09/05/03
* @interface new Debug()
*/
function Debug() {
this.debugWindow = window.open("../debug/debug.html", "debug", "width=400,height=600,resizable=yes,scrollbars=yes");
}
/**
* Clears the contents of the debug window. * * @author Stuart Wigley * @author Randolph Fielding * @version 1.1, 09/05/03 * @interfaceDebug.clear()
* @returntrue
if no exceptions are encountered * @returnnull
if an exception is encountered * @throws IllegalArgumentException * @throws UnknownException */
Debug.prototype.clear = function() {
try { var vError = null; var iNumArguments = arguments.length; if (iNumArguments != 0) { throw vError = new IllegalArgumentException("Debug.clear", 0, iNumArguments); } var oMessageContainer = document.getElementById("messageContainer"); if (!oMessageContainer) { throw vError = new UnknownException("Debug.clear"); } while (oMessageContainer.hasChildNodes()) { oMessageContainer.removeChild(oMessageContainer.firstChild); } } catch (vError) { if (vError instanceof Error) { vError.handleError(); } } finally { return vError ? null : true; }
}
/**
* Displays content within the debug window. * * @author Stuart Wigley * @author Randolph Fielding * @version 1.2, 09/05/03 * @interfaceDebug.print(vMixedValue)
* @interfaceDebug.print(vMixedValue, iMessageType)
* @param vMixedValue content to be displayed within the debug window * @param iMessageType an integer representing the type of content to display * within the debug window (information: 0; error: 1) * (optional) * @returntrue
if no exceptions are encountered * @returnnull
if an exception is encountered * @throws IllegalArgumentException * @throws IllegalValueException * @throws TypeMismatchException * @throws UnknownException */
Debug.prototype.print = function(vMixedValue) {
try { var vError = null; var iNumArguments = arguments.length; var iMessageType = 0; if ((iNumArguments < 1) || (iNumArguments > 2)) { throw vError = new IllegalArgumentException("Debug.print", "1 or 2", iNumArguments); } else if (iNumArguments == 2) { iMessageType = arguments[1]; } if ((typeof iMessageType != "number") || (iMessageType.toString().indexOf(".") != -1)) { throw vError = new TypeMismatchException("Debug.print", "integer", typeof iMessageType); } if ((iMessageType != 0) && (iMessageType != 1)) { throw vError = new IllegalValueException("Debug.print", "iMessageType", "0 or 1", iMessageType); } var oDebugWindow = this.debugWindow; if (!oDebugWindow || oDebugWindow.closed) { throw vError = new UnknownException("Debug.print"); } var oDocument = oDebugWindow.document; if (!oDocument) { throw vError = new UnknownException("Debug.print"); } var oMessageContainer = oDocument.getElementById("messageContainer"); if (!oMessageContainer) { throw vError = new UnknownException("Debug.print"); } var oTitleRow = oDocument.createElement("tr"); var oTitleCell = oDocument.createElement("td"); var oBodyRow = oDocument.createElement("tr"); var oBodyCell = oDocument.createElement("td"); if (!oTitleRow || !oTitleCell || !oBodyRow || !oBodyCell) { throw vError = new UnknownException("Debug.print"); } var oTitleRowStyle = oTitleRow.style; if (oTitleRowStyle) { oTitleRowStyle.backgroundColor = "#EEE"; oTitleRowStyle.fontWeight = 700; } var sOutputString = vMixedValue.toString(); var sTitle = "info"; var sBody = sOutputString; if (iMessageType == 1) { sTitle = sOutputString.match(/\w+/); sBody = sOutputString.replace(/\w+/, ""); var oBodyCellStyle = oBodyCell.style; if (oBodyCellStyle) { oBodyCell.style.backgroundColor = "#FCC"; } } oMessageContainer.appendChild(oTitleRow); oTitleRow.appendChild(oTitleCell); oTitleCell.appendChild(oDocument.createTextNode(sTitle)); oMessageContainer.appendChild(oBodyRow); oBodyRow.appendChild(oBodyCell); oBodyCell.appendChild(oDocument.createTextNode(sBody)); oDebugWindow.focus(); } catch (vError) { if (vError instanceof Error) { vError.handleError(); } } finally { return vError ? null : true; }
}
</script> <script type="text/javascript">
/**
* +-------------------------------------------------------------------------+ * | jsPro - Test | * +-------------------------------------------------------------------------+ * | Copyright (C) 2001-2003 Stuart Wigley | * +-------------------------------------------------------------------------+ * | This library is free software; you can redistribute it and/or modify it | * | under the terms of the GNU Lesser General Public License as published by| * | the Free Software Foundation; either version 2.1 of the License, or (at | * | your option) any later version. | * | | * | This library is distributed in the hope that it will be useful, but | * | WITHOUT ANY WARRANTY; without even the implied warranty of | * | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser | * | General Public License for more details. | * | | * | You should have received a copy of the GNU Lesser General Public License| * | along with this library; if not, write to the Free Software Foundation, | * | Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA | * +-------------------------------------------------------------------------+ * | Authors: Stuart Wigley <stuartwigley@yahoo.co.uk> | * | Randolph Fielding <gator4life@cinci.rr.ru> | * +-------------------------------------------------------------------------+ * $Id: test.js,v 1.6 2003/09/15 05:07:09 gator4life Exp $ */
/**
* Creates an object that provides methods for testing all jsPro libraries.
*
* @author Stuart Wigley
* @version 1.0, 07/24/03
* @interface new Test()
*/
function Test() { }
/**
* Evaluates and returns the result of a jsPro method using assumptions about * the structure and ids of HTML elements in the jsPro HTML test files. * * @author Stuart Wigley * @author Randolph Fielding * @version 1.1, 08/20/03 * @interfaceTest.evaluateMethod(oButton, sClass)
* @param oButton the HTML input-button element that is clicked * @param sClass the name of the jsPro class instance being tested * @return the result of attempting to evaluate a jsPro method * @returnnull
if an exception is encountered * @throws IllegalArgumentException * @throws TypeMismatchException */
Test.prototype.evaluateMethod = function(oButton, sClass) {
try { var vError = null; var iNumArguments = arguments.length; if (iNumArguments != 2) { throw vError = new IllegalArgumentException("Error.evaluateMethod", 2, iNumArguments); } if (typeof oButton != "object") { throw vError = new TypeMismatchException("Error.evaluateMethod", "object", typeof oButton); } if (typeof sClass != "string") { throw vError = new TypeMismatchException("Error.evaluateMethod", "string", typeof sClass); } var sMethodName = oButton.id; var oInput1 = document.getElementById(sMethodName + "1"); var oInput2 = document.getElementById(sMethodName + "2"); var oInput3 = document.getElementById(sMethodName + "3"); var oOutput = document.getElementById(sMethodName + "Result"); var sArguments = ""; if (oInput1) { var sInput1Value = oInput1.value; if (sInput1Value != "") { var fInput1Value = parseFloat(sInput1Value); sArguments += (isNaN(fInput1Value)) ? "\"" + sInput1Value + "\"" : fInput1Value; } } if (oInput2) { var sInput2Value = oInput2.value; if (sInput2Value != "") { var fInput2Value = parseFloat(sInput2Value); sArguments += (isNaN(fInput2Value)) ? ", \"" + sInput2Value + "\"" : ", " + fInput2Value; } } if (oInput3) { var sInput3Value = oInput3.value; if (sInput3Value != "") { var fInput3Value = parseFloat(sInput3Value); sArguments += (isNaN(fInput3Value)) ? ", \"" + sInput3Value + "\"" : ", " + fInput3Value; } } var vResult = eval(sClass + "." + sMethodName + "(" + sArguments + ")"); } catch (vError) { if (vError instanceof Error) { vError.handleError(); } } finally { if (oOutput) { oOutput.value = vResult; } }
}
</script> <script type="text/javascript">
/**
* +-------------------------------------------------------------------------+ * | jsPro - Array | * +-------------------------------------------------------------------------+ * | Copyright (C) 2001-2003 Stuart Wigley | * +-------------------------------------------------------------------------+ * | This library is free software; you can redistribute it and/or modify it | * | under the terms of the GNU Lesser General Public License as published by| * | the Free Software Foundation; either version 2.1 of the License, or (at | * | your option) any later version. | * | | * | This library is distributed in the hope that it will be useful, but | * | WITHOUT ANY WARRANTY; without even the implied warranty of | * | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser | * | General Public License for more details. | * | | * | You should have received a copy of the GNU Lesser General Public License| * | along with this library; if not, write to the Free Software Foundation, | * | Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA | * +-------------------------------------------------------------------------+ * | Authors: Stuart Wigley <stuartwigley@yahoo.co.uk> | * | Randolph Fielding <gator4life@cinci.rr.ru> | * +-------------------------------------------------------------------------+ * $Id: array.js,v 1.28 2003/09/22 06:02:21 gator4life Exp $ */
/**
* Calculates and returns the average deviation of all array members or of a * subset of array members (if the optional start and length arguments are * specified). * * @summary average deviation * @author Stuart Wigley * @version 1.0, 09/19/03 * @interfaceArray.averageDev()
* @interfaceArray.averageDev(iStart)
* @interfaceArray.averageDev(iStart, iLength)
* @requiresArray.mean(iStart, iLength)
* @param iStart the index of the array member to start at (optional) * @param iLength the number of array members to evaluate beginning at *iStart
(optional) * @return the average deviation of all array members or of a * subset of array members * @returnnull
if an exception is encountered * @throws ArrayIndexOutOfBoundsException * @throws IllegalArgumentException * @throws MethodNotAvailableException * @throws TypeMismatchException * @throws UnknownException * @seeArray.mean()
*/
Array.prototype.averageDev = function() {
try { var vError = null; var iArrayLength = this.length; var iNumArguments = arguments.length; var iStart = 0; var iLength = iArrayLength; if (!("mean" in this)) { throw vError = new MethodNotAvailableException("Array.averageDev", "Array.mean"); } if (iNumArguments > 2) { throw vError = new IllegalArgumentException("Array.averageDev", "0, 1 or 2", iNumArguments); } else if (iNumArguments == 2) { iStart = arguments[0]; iLength = arguments[1]; } else if (iNumArguments == 1) { iStart = arguments[0]; iLength -= iStart; } if ((typeof iStart != "number") || (iStart.toString().indexOf(".") != -1)) { throw vError = new TypeMismatchException("Array.averageDev", "integer", typeof iStart); } if ((typeof iLength != "number") || (iLength.toString().indexOf(".") != -1)) { throw vError = new TypeMismatchException("Array.averageDev", "integer", typeof iLength); } var iEnd = iStart + iLength; if (iStart < 0) { throw vError = new ArrayIndexOutOfBoundsException("Array.averageDev", iStart, iArrayLength); } if (iLength <= 0) { throw vError = new ArrayIndexOutOfBoundsException("Array.averageDev", iLength, iArrayLength); } if (iEnd > iArrayLength) { throw vError = new ArrayIndexOutOfBoundsException("Array.averageDev", iEnd, iArrayLength); } var fMean = this.mean(iStart, iEnd); if (!fMean) { throw vError = new UnknownException("Array.averageDev"); } var aAbsoluteDevs = new Array(); var iCount = 0; for (var i = iStart; i < iEnd; i++) { if (typeof this[i] == "number") { aAbsoluteDevs[iCount] = Math.abs(this[i] - fMean); iCount++; } } var fAverageDev = aAbsoluteDevs.mean(); if (!fAverageDev) { throw vError = new UnknownException("Array.averageDev"); } } catch (vError) { if (vError instanceof Error) { vError.handleError(); } } finally { return vError ? null : fAverageDev; }
}
/**
* Changes the case of all array keys to lowercase or uppercase. * * @summary change key case * @author Stuart Wigley * @author Randolph Fielding * @version 1.1, 09/14/03 * @interfaceArray.changeKeyCase(iCase)
* @param iCase an integer representing the case to change array keys * to (lowercase: 0; uppercase: 1) * @return an array with keys changed to lowercase or uppercase * @returnnull
if an exception is encountered * @throws IllegalArgumentException * @throws IllegalValueException * @throws TypeMismatchException */
Array.prototype.changeKeyCase = function(iCase) {
try { var vError = null; var iNumArguments = arguments.length; if (iNumArguments != 1) { throw vError = new IllegalArgumentException("Array.changeKeyCase", 1, iNumArguments); } if ((typeof iCase != "number") || (iCase.toString().indexOf(".") != -1)) { throw vError = new TypeMismatchException("Array.changeKeyCase", "integer", typeof iCase); } if ((iCase != 0) && (iCase != 1)) { throw vError = new IllegalValueException("Array.changeKeyCase", "iCase", "0 or 1", iCase); } for (var sKey in this) { if (this.hasOwnProperty(sKey)) { var sKeyCase = (iCase == 1) ? sKey.toUpperCase() : sKey.toLowerCase(); if (sKeyCase != sKey) { this[sKeyCase] = this[sKey]; delete this[sKey]; } } } } catch (vError) { if (vError instanceof Error) { vError.handleError(); } } finally { return vError ? null : this; }
}
/**
* Returns an array of "chunks" where each "chunk" is an array of *iChunkSize
formed from this array. * * @summary split into chunks * @author Stuart Wigley * @author Randolph Fielding * @version 1.2, 06/27/03 * @interfaceArray.chunk(iChunkSize)
* @param iChunkSize the size of a "chunk" formed from this array * @return an array of "chunks" formed from this array * @returnnull
if an exception is encountered * @throws ArrayIndexOutOfBoundsException * @throws IllegalArgumentException * @throws TypeMismatchException */
Array.prototype.chunk = function(iChunkSize) {
try { var vError = null; var iArrayLength = this.length; var iNumArguments = arguments.length; if (iNumArguments != 1) { throw vError = new IllegalArgumentException("Array.chunk", 1, iNumArguments); } if ((typeof iChunkSize != "number") || (iChunkSize.toString().indexOf(".") != -1)) { throw vError = new TypeMismatchException("Array.chunk", "integer", typeof iChunkSize); } if ((iChunkSize <= 0) || (iChunkSize > iArrayLength)) { throw vError = new ArrayIndexOutOfBoundsException("Array.chunk", iChunkSize, iArrayLength); } var iChunkedArrayLength = Math.ceil(iArrayLength / iChunkSize); var aChunkedArray = new Array(iChunkedArrayLength); var iSourceArrayIndex = 0; for (var i = 0; i < iChunkedArrayLength; i++) { aChunkedArray[i] = new Array(iChunkSize); for (var j = 0; j < iChunkSize; j++) { aChunkedArray[i][j] = this[iSourceArrayIndex++]; } } } catch (vError) { if (vError instanceof Error) { vError.handleError(); } } finally { return vError ? null : aChunkedArray; }
}
/**
* Returns an associative array keyed on the values of this array. Each member * of the associative array contains an integer value representing the number * of occurrences of that member"s key in this array. * * @summary count occurrence of values * @author Stuart Wigley * @author Randolph Fielding * @version 1.2, 06/29/03 * @interfaceArray.count()
* @return an associative array of counted values * @returnnull
if an exception is encountered * @throws IllegalArgumentException */
Array.prototype.count = function() {
try { var vError = null; var iNumArguments = arguments.length; if (iNumArguments > 0) { throw vError = new IllegalArgumentException("Array.count", 0, iNumArguments); } var iArrayLength = this.length; var aCountedArray = new Array(); for (var i = 0; i < iArrayLength; i++) { var sValue = this[i].toString(); aCountedArray[sValue] = (aCountedArray[sValue] == undefined) ? 1 : ++aCountedArray[sValue]; } } catch (vError) { if (vError instanceof Error) { vError.handleError(); } } finally { return vError ? null : aCountedArray; }
}
/**
* Calculates and returns the coefficient of variation of all array members or * of a subset of array members (if the optional start and length arguments are * specified). * * @summary coefficient of variation * @author Stuart Wigley * @author Randolph Fielding * @version 1.4, 08/08/03 * @interfaceArray.covar()
* @interfaceArray.covar(iStart)
* @interfaceArray.covar(iStart, iLength)
* @requiresArray.mean(iStart, iLength)
* @requiresArray.standardDev(iStart, iLength)
* @param iStart the index of the array member to start at (optional) * @param iLength the number of array members to evaluate beginning at *iStart
(optional) * @return the coefficient of variation of all array members or of * a subset of array members * @returnnull
if an exception is encountered * @throws ArrayIndexOutOfBoundsException * @throws IllegalArgumentException * @throws MethodNotAvailableException * @throws TypeMismatchException * @throws UnknownException * @seeArray.mean()
* @seeArray.standardDev()
*/
Array.prototype.covar = function() {
try { var vError = null; var iArrayLength = this.length; var iNumArguments = arguments.length; var iStart = 0; var iLength = iArrayLength; if (!("mean" in this)) { throw vError = new MethodNotAvailableException("Array.covar", "Array.mean"); } if (!("standardDev" in this)) { throw vError = new MethodNotAvailableException("Array.covar", "Array.standardDev"); } if (iNumArguments > 2) { throw vError = new IllegalArgumentException("Array.covar", "0, 1 or 2", iNumArguments); } else if (iNumArguments == 2) { iStart = arguments[0]; iLength = arguments[1]; } else if (iNumArguments == 1) { iStart = arguments[0]; iLength -= iStart; } if ((typeof iStart != "number") || (iStart.toString().indexOf(".") != -1)) { throw vError = new TypeMismatchException("Array.covar", "integer", typeof iStart); } if ((typeof iLength != "number") || (iLength.toString().indexOf(".") != -1)) { throw vError = new TypeMismatchException("Array.covar", "integer", typeof iLength); } var iEnd = iStart + iLength; if (iStart < 0) { throw vError = new ArrayIndexOutOfBoundsException("Array.covar", iStart, iArrayLength); } if (iLength <= 0) { throw vError = new ArrayIndexOutOfBoundsException("Array.covar", iLength, iArrayLength); } if (iEnd > iArrayLength) { throw vError = new ArrayIndexOutOfBoundsException("Array.covar", iEnd, iArrayLength); } var fMean = this.mean(iStart, iLength); var fStandardDev = this.standardDev(iStart, iLength); if (!fMean || !fStandardDev) { throw vError = new UnknownException("Array.covar"); } var fCovar = fStandardDev / fMean; } catch (vError) { if (vError instanceof Error) { vError.handleError(); } } finally { return vError ? null : fCovar; }
}
/**
* Fills this array or a subset of array members (if the optional start and * length arguments are specified) with a value of any data type. * * @summary fill * @author Stuart Wigley * @author Randolph Fielding * @version 1.1, 06/28/03 * @interfaceArray.fill(vFill)
* @interfaceArray.fill(vFill, iStart)
* @interfaceArray.fill(vFill, iStart, iLength)
* @param vFill a value of any data type to fill this array or a * subset of array members with * @param iStart the index of the array member to start at (optional) * @param iLength the number of array members to fill beginning at *iStart
(optional) * @return a modified array * @returnnull
if an exception is encountered * @throws ArrayIndexOutOfBoundsException * @throws IllegalArgumentException * @throws TypeMismatchException */
Array.prototype.fill = function(vFill) {
try { var vError = null; var iArrayLength = this.length; var iNumArguments = arguments.length; var iStart = 0; var iLength = iArrayLength; if ((iNumArguments < 1) || (iNumArguments > 3)) { throw vError = new IllegalArgumentException("Array.fill", "1, 2 or 3", iNumArguments); } else if (iNumArguments == 3) { iStart = arguments[1]; iLength = arguments[2]; } else if (iNumArguments == 2) { iStart = arguments[1]; iLength -= iStart; } if ((typeof iStart != "number") || (iStart.toString().indexOf(".") != -1)) { throw vError = new TypeMismatchException("Array.fill", "integer", typeof iStart); } if ((typeof iLength != "number") || (iLength.toString().indexOf(".") != -1)) { throw vError = new TypeMismatchException("Array.fill", "integer", typeof iLength); } var iEnd = iStart + iLength; if (iStart < 0) { throw vError = new ArrayIndexOutOfBoundsException("Array.fill", iStart, iArrayLength); } if (iLength <= 0) { throw vError = new ArrayIndexOutOfBoundsException("Array.fill", iLength, iArrayLength); } if (iEnd > iArrayLength) { throw vError = new ArrayIndexOutOfBoundsException("Array.fill", iEnd, iArrayLength); } for (var i = iStart; i < iEnd; i++) { this[i] = vFill; } } catch (vError) { if (vError instanceof Error) { vError.handleError(); } } finally { return vError ? null : this; }
}
/**
* Returns the maximum numerical value contained in this array or in a subset * of array members (if the optional start and length arguments are specified). * * @summary maximum value * @author Stuart Wigley * @author Randolph Fielding * @version 1.1, 06/27/03 * @interfaceArray.max()
* @interfaceArray.max(iStart)
* @interfaceArray.max(iStart, iLength)
* @param iStart the index of the array member to start at (optional) * @param iLength the number of array members to evaluate beginning at *iStart
(optional) * @return the maximum numerical value contained in this array or * in a subset of array members * @returnnull
if no array members are numbers * @returnnull
if an exception is encountered * @throws ArrayIndexOutOfBoundsException * @throws IllegalArgumentException * @throws TypeMismatchException */
Array.prototype.max = function() {
try { var vError = null; var iArrayLength = this.length; var iNumArguments = arguments.length; var iStart = 0; var iLength = iArrayLength; if (iNumArguments > 2) { throw vError = new IllegalArgumentException("Array.max", "0, 1 or 2", iNumArguments); } else if (iNumArguments == 2) { iStart = arguments[0]; iLength = arguments[1]; } else if (iNumArguments == 1) { iStart = arguments[0]; iLength -= iStart; } if ((typeof iStart != "number") || (iStart.toString().indexOf(".") != -1)) { throw vError = new TypeMismatchException("Array.max", "integer", typeof iStart); } if ((typeof iLength != "number") || (iLength.toString().indexOf(".") != -1)) { throw vError = new TypeMismatchException("Array.max", "integer", typeof iLength); } var iEnd = iStart + iLength; if (iStart < 0) { throw vError = new ArrayIndexOutOfBoundsException("Array.max", iStart, iArrayLength); } if (iLength <= 0) { throw vError = new ArrayIndexOutOfBoundsException("Array.max", iLength, iArrayLength); } if (iEnd > iArrayLength) { throw vError = new ArrayIndexOutOfBoundsException("Array.max", iEnd, iArrayLength); } var fMax = null; for (var i = iStart; i < iEnd; i++) { if ((typeof this[i] == "number") && ((fMax == null) || (this[i] > fMax))) { fMax = this[i]; } } } catch (vError) { if (vError instanceof Error) { vError.handleError(); } } finally { return vError ? null : fMax; }
}
/**
* Calculates and returns the mean of all array members or of a subset of array * members (if the optional start and length arguments are specified). * * @summary mean * @author Stuart Wigley * @author Randolph Fielding * @version 1.5, 08/08/03 * @interfaceArray.mean()
* @interfaceArray.mean(iStart)
* @interfaceArray.mean(iStart, iLength)
* @param iStart the index of the array member to start at (optional) * @param iLength the number of array members to evaluate beginning at *iStart
(optional) * @return the mean of all array members or of a subset of array * members * @returnnull
if no array members are numbers * @returnnull
if an exception is encountered * @throws ArrayIndexOutOfBoundsException * @throws IllegalArgumentException * @throws TypeMismatchException */
Array.prototype.mean = function() {
try { var vError = null; var iArrayLength = this.length; var iNumArguments = arguments.length; var iStart = 0; var iLength = iArrayLength; if (iNumArguments > 2) { throw vError = new IllegalArgumentException("Array.mean", "0, 1 or 2", iNumArguments); } else if (iNumArguments == 2) { iStart = arguments[0]; iLength = arguments[1]; } else if (iNumArguments == 1) { iStart = arguments[0]; iLength -= iStart; } if ((typeof iStart != "number") || (iStart.toString().indexOf(".") != -1)) { throw vError = new TypeMismatchException("Array.mean", "integer", typeof iStart); } if ((typeof iLength != "number") || (iLength.toString().indexOf(".") != -1)) { throw vError = new TypeMismatchException("Array.mean", "integer", typeof iLength); } var iEnd = iStart + iLength; if (iStart < 0) { throw vError = new ArrayIndexOutOfBoundsException("Array.mean", iStart, iArrayLength); } if (iLength <= 0) { throw vError = new ArrayIndexOutOfBoundsException("Array.mean", iLength, iArrayLength); } if (iEnd > iArrayLength) { throw vError = new ArrayIndexOutOfBoundsException("Array.mean", iEnd, iArrayLength); } var fSum = 0; var iCount = 0; for (var i = iStart; i < iEnd; i++) { if (typeof this[i] == "number") { fSum += this[i]; iCount++; } } var fMean = (iCount == 0) ? null : fSum / iCount; } catch (vError) { if (vError instanceof Error) { vError.handleError(); } } finally { return vError ? null : fMean; }
}
/**
* Calculates and returns the median of all array members or of a subset of * array members (if the optional start and length arguments are specified). * * @summary median * @author Stuart Wigley * @author Randolph Fielding * @version 1.2, 08/08/03 * @interfaceArray.median()
* @interfaceArray.median(iStart)
* @interfaceArray.median(iStart, iLength)
* @param iStart the index of the array member to start at (optional) * @param iLength the number of array members to evaluate beginning at *iStart
(optional) * @return the median of all array members or of a subset of array * members * @returnnull
if no array members are numbers * @returnnull
if an exception is encountered * @throws ArrayIndexOutOfBoundsException * @throws IllegalArgumentException * @throws TypeMismatchException */
Array.prototype.median = function() {
try { var vError = null; var iArrayLength = this.length; var iNumArguments = arguments.length; var iStart = 0; var iLength = iArrayLength; if (iNumArguments > 2) { throw vError = new IllegalArgumentException("Array.median", "0, 1 or 2", iNumArguments); } else if (iNumArguments == 2) { iStart = arguments[0]; iLength = arguments[1]; } else if (iNumArguments == 1) { iStart = arguments[0]; iLength -= iStart; } if ((typeof iStart != "number") || (iStart.toString().indexOf(".") != -1)) { throw vError = new TypeMismatchException("Array.median", "integer", typeof iStart); } if ((typeof iLength != "number") || (iLength.toString().indexOf(".") != -1)) { throw vError = new TypeMismatchException("Array.median", "integer", typeof iLength); } var iEnd = iStart + iLength; if (iStart < 0) { throw vError = new ArrayIndexOutOfBoundsException("Array.median", iStart, iArrayLength); } if (iLength <= 0) { throw vError = new ArrayIndexOutOfBoundsException("Array.median", iLength, iArrayLength); } if (iEnd > iArrayLength) { throw vError = new ArrayIndexOutOfBoundsException("Array.median", iEnd, iArrayLength); } var aTempArray = new Array(); var iTempArrayIndex = 0; for (var i = iStart; i < iEnd; i++) { if (typeof this[i] == "number") { aTempArray[iTempArrayIndex++] = this[i]; } } var iTempArrayLength = aTempArray.length; var iModTempArrayLength = iTempArrayLength - 1; for (var j = 0; j < iModTempArrayLength; j++) { for (var k = j + 1; k < iTempArrayLength; k++) { if (aTempArray[k] < aTempArray[j]) { var fValue = aTempArray[j]; aTempArray[j] = aTempArray[k]; aTempArray[k] = fValue; } } } var fMedian = (iTempArrayLength == 0) ? null : (iTempArrayLength % 2 == 1) ? aTempArray[Math.floor(iTempArrayLength / 2)] : (aTempArray[iTempArrayLength / 2] + aTempArray[(iTempArrayLength / 2) - 1]) / 2; } catch (vError) { if (vError instanceof Error) { vError.handleError(); } } finally { return vError ? null : fMedian; }
}
/**
* Returns the minimum numerical value contained in this array or in a subset * of array members (if the optional start and length arguments are specified). * * @summary minimum value * @author Stuart Wigley * @author Randolph Fielding * @version 1.2, 06/27/03 * @interfaceArray.min()
* @interfaceArray.min(iStart)
* @interfaceArray.min(iStart, iLength)
* @param iStart the index of the array member to start at (optional) * @param iLength the number of array members to evaluate beginning at *iStart
(optional) * @return the minimum numerical value contained in this array or * in a subset of array members * @returnnull
if no array members are numbers * @returnnull
if an exception is encountered * @throws ArrayIndexOutOfBoundsException * @throws IllegalArgumentException * @throws TypeMismatchException */
Array.prototype.min = function() {
try { var vError = null; var iArrayLength = this.length; var iNumArguments = arguments.length; var iStart = 0; var iLength = iArrayLength; if (iNumArguments > 2) { throw vError = new IllegalArgumentException("Array.min", "0, 1 or 2", iNumArguments); } else if (iNumArguments == 2) { iStart = arguments[0]; iLength = arguments[1]; } else if (iNumArguments == 1) { iStart = arguments[0]; iLength -= iStart; } if ((typeof iStart != "number") || (iStart.toString().indexOf(".") != -1)) { throw vError = new TypeMismatchException("Array.min", "integer", typeof iStart); } if ((typeof iLength != "number") || (iLength.toString().indexOf(".") != -1)) { throw vError = new TypeMismatchException("Array.min", "integer", typeof iLength); } var iEnd = iStart + iLength; if (iStart < 0) { throw vError = new ArrayIndexOutOfBoundsException("Array.min", iStart, iArrayLength); } if (iLength <= 0) { throw vError = new ArrayIndexOutOfBoundsException("Array.min", iLength, iArrayLength); } if (iEnd > iArrayLength) { throw vError = new ArrayIndexOutOfBoundsException("Array.min", iEnd, iArrayLength); } var fMin = null; for (var i = iStart; i < iEnd; i++) { if ((typeof this[i] == "number") && ((fMin == null) || (this[i] < fMin))) { fMin = this[i]; } } } catch (vError) { if (vError instanceof Error) { vError.handleError(); } } finally { return vError ? null : fMin; }
}
/**
* Calculates and returns the product of all array members or of a subset of * array members (if the optional start and length arguments are specified). * * @summary product * @author Stuart Wigley * @author Randolph Fielding * @version 1.2, 08/08/03 * @interfaceArray.product()
* @interfaceArray.product(iStart)
* @interfaceArray.product(iStart, iLength)
* @param iStart the index of the array member to start at (optional) * @param iLength the number of array members to evaluate beginning at *iStart
(optional) * @return the product of all array members or of a subset of * array members * @returnnull
if no array members are numbers * @returnnull
if an exception is encountered * @throws ArrayIndexOutOfBoundsException * @throws IllegalArgumentException * @throws TypeMismatchException */
Array.prototype.product = function() {
try { var vError = null; var iArrayLength = this.length; var iNumArguments = arguments.length; var iStart = 0; var iLength = iArrayLength; if (iNumArguments > 2) { throw vError = new IllegalArgumentException("Array.product", "0, 1 or 2", iNumArguments); } else if (iNumArguments == 2) { iStart = arguments[0]; iLength = arguments[1]; } else if (iNumArguments == 1) { iStart = arguments[0]; iLength -= iStart; } if ((typeof iStart != "number") || (iStart.toString().indexOf(".") != -1)) { throw vError = new TypeMismatchException("Array.product", "integer", typeof iStart); } if ((typeof iLength != "number") || (iLength.toString().indexOf(".") != -1)) { throw vError = new TypeMismatchException("Array.product", "integer", typeof iLength); } var iEnd = iStart + iLength; if (iStart < 0) { throw vError = new ArrayIndexOutOfBoundsException("Array.product", iStart, iArrayLength); } if (iLength <= 0) { throw vError = new ArrayIndexOutOfBoundsException("Array.product", iLength, iArrayLength); } if (iEnd > iArrayLength) { throw vError = new ArrayIndexOutOfBoundsException("Array.product", iEnd, iArrayLength); } var fProduct = 1; var iCount = 0; for (var i = iStart; i < iEnd; i++) { if (typeof this[i] == "number") { fProduct *= this[i]; iCount++; } } fProduct = (iCount == 0) ? null : fProduct; } catch (vError) { if (vError instanceof Error) { vError.handleError(); } } finally { return vError ? null : fProduct; }
}
/**
* Calculates and returns the range of all array members or of a subset of * array members (if the optional start and length arguments are specified). * * @summary range * @author Stuart Wigley * @author Randolph Fielding * @version 1.2, 08/08/03 * @interfaceArray.range()
* @interfaceArray.range(iStart)
* @interfaceArray.range(iStart, iLength)
* @requiresArray.max(iStart, iLength)
* @requiresArray.min(iStart, iLength)
* @param iStart the index of the array member to start at (optional) * @param iLength the number of array members to evaluate beginning at *iStart
(optional) * @return the range of all array members or of a subset of array * members * @returnnull
if an exception is encountered * @throws ArrayIndexOutOfBoundsException * @throws IllegalArgumentException * @throws MethodNotAvailableException * @throws TypeMismatchException * @throws UnknownException * @seeArray.max()
* @seeArray.min()
*/
Array.prototype.range = function() {
try { var vError = null; var iArrayLength = this.length; var iNumArguments = arguments.length; var iStart = 0; var iLength = iArrayLength; if (!("max" in this)) { throw vError = new MethodNotAvailableException("Array.range", "Array.max"); } if (!("min" in this)) { throw vError = new MethodNotAvailableException("Array.range", "Array.min"); } if (iNumArguments > 2) { throw vError = new IllegalArgumentException("Array.range", "0, 1 or 2", iNumArguments); } else if (iNumArguments == 2) { iStart = arguments[0]; iLength = arguments[1]; } else if (iNumArguments == 1) { iStart = arguments[0]; iLength -= iStart; } if ((typeof iStart != "number") || (iStart.toString().indexOf(".") != -1)) { throw vError = new TypeMismatchException("Array.range", "integer", typeof iStart); } if ((typeof iLength != "number") || (iLength.toString().indexOf(".") != -1)) { throw vError = new TypeMismatchException("Array.range", "integer", typeof iLength); } var iEnd = iStart + iLength; if (iStart < 0) { throw vError = new ArrayIndexOutOfBoundsException("Array.range", iStart, iArrayLength); } if (iLength <= 0) { throw vError = new ArrayIndexOutOfBoundsException("Array.range", iLength, iArrayLength); } if (iEnd > iArrayLength) { throw vError = new ArrayIndexOutOfBoundsException("Array.range", iEnd, iArrayLength); } var fMax = this.max(iStart, iLength); var fMin = this.min(iStart, iLength); if (!fMax || !fMin) { throw vError = new UnknownException("Array.range"); } var fRange = fMax - fMin; } catch (vError) { if (vError instanceof Error) { vError.handleError(); } } finally { return vError ? null : fRange; }
}
/**
* Calculates and returns the standard deviation of all array members or of a * subset of array members (if the optional start and length arguments are * specified). * * @summary standard deviation * @author Stuart Wigley * @author Randolph Fielding * @version 1.4, 08/08/03 * @interfaceArray.standardDev()
* @interfaceArray.standardDev(iStart)
* @interfaceArray.standardDev(iStart, iLength)
* @requiresArray.variance(iStart, iLength)
* @param iStart the index of the array member to start at (optional) * @param iLength the number of array members to evaluate beginning at *iStart
(optional) * @return the standard deviation of all array members or of a * subset of array members * @returnnull
if an exception is encountered * @throws ArrayIndexOutOfBoundsException * @throws IllegalArgumentException * @throws MethodNotAvailableException * @throws TypeMismatchException * @throws UnknownException * @seeArray.variance()
*/
Array.prototype.standardDev = function() {
try { var vError = null; var iArrayLength = this.length; var iNumArguments = arguments.length; var iStart = 0; var iLength = iArrayLength; if (!("variance" in this)) { throw vError = new MethodNotAvailableException("Array.standardDev", "Array.variance"); } if (iNumArguments > 2) { throw vError = new IllegalArgumentException("Array.standardDev", "0, 1 or 2", iNumArguments); } else if (iNumArguments == 2) { iStart = arguments[0]; iLength = arguments[1]; } else if (iNumArguments == 1) { iStart = arguments[0]; iLength -= iStart; } if ((typeof iStart != "number") || (iStart.toString().indexOf(".") != -1)) { throw vError = new TypeMismatchException("Array.standardDev", "integer", typeof iStart); } if ((typeof iLength != "number") || (iLength.toString().indexOf(".") != -1)) { throw vError = new TypeMismatchException("Array.standardDev", "integer", typeof iLength); } var iEnd = iStart + iLength; if (iStart < 0) { throw vError = new ArrayIndexOutOfBoundsException("Array.standardDev", iStart, iArrayLength); } if (iLength <= 0) { throw vError = new ArrayIndexOutOfBoundsException("Array.standardDev", iLength, iArrayLength); } if (iEnd > iArrayLength) { throw vError = new ArrayIndexOutOfBoundsException("Array.standardDev", iEnd, iArrayLength); } var fVariance = this.variance(iStart, iLength); if (!fVariance) { throw vError = new UnknownException("Array.standardDev"); } var fStandardDev = Math.sqrt(fVariance); } catch (vError) { if (vError instanceof Error) { vError.handleError(); } } finally { return vError ? null : fStandardDev; }
}
/**
* Calculates and returns the sum of all array members or of a subset of array * members (if the optional start and length arguments are specified). * * @summary sum * @author Stuart Wigley * @author Randolph Fielding * @version 1.2, 08/08/03 * @interfaceArray.sum()
* @interfaceArray.sum(iStart)
* @interfaceArray.sum(iStart, iLength)
* @param iStart the index of the array member to start at (optional) * @param iLength the number of array members to evaluate beginning at *iStart
(optional) * @return the sum of all array members or of a subset of array * members * @returnnull
if no array members are numbers * @returnnull
if an exception is encountered * @throws ArrayIndexOutOfBoundsException * @throws IllegalArgumentException * @throws TypeMismatchException */
Array.prototype.sum = function() {
try { var vError = null; var iArrayLength = this.length; var iNumArguments = arguments.length; var iStart = 0; var iLength = iArrayLength; if (iNumArguments > 2) { throw vError = new IllegalArgumentException("Array.sum", "0, 1 or 2", iNumArguments); } else if (iNumArguments == 2) { iStart = arguments[0]; iLength = arguments[1]; } else if (iNumArguments == 1) { iStart = arguments[0]; iLength -= iStart; } if ((typeof iStart != "number") || (iStart.toString().indexOf(".") != -1)) { throw vError = new TypeMismatchException("Array.sum", "integer", typeof iStart); } if ((typeof iLength != "number") || (iLength.toString().indexOf(".") != -1)) { throw vError = new TypeMismatchException("Array.sum", "integer", typeof iLength); } var iEnd = iStart + iLength; if (iStart < 0) { throw vError = new ArrayIndexOutOfBoundsException("Array.sum", iStart, iArrayLength); } if (iLength <= 0) { throw vError = new ArrayIndexOutOfBoundsException("Array.sum", iLength, iArrayLength); } if (iEnd > iArrayLength) { throw vError = new ArrayIndexOutOfBoundsException("Array.sum", iEnd, iArrayLength); } var fSum = 0; var iCount = 0; for (var i = iStart; i < iEnd; i++) { if (typeof this[i] == "number") { fSum += this[i]; iCount++; } } fSum = (iCount == 0) ? null : fSum; } catch (vError) { if (vError instanceof Error) { vError.handleError(); } } finally { return vError ? null : fSum; }
}
/**
* Swaps the values of two array members at the specified indices. * * @summary swap two members * @author Stuart Wigley * @author Randolph Fielding * @version 1.1, 06/27/03 * @interfaceArray.swap(iIndex1, iIndex2)
* @param iIndex1 the index of an array member * @param iIndex2 the index of an array member * @return a modified array * @returnnull
if an exception is encountered * @throws ArrayIndexOutOfBoundsException * @throws IllegalArgumentException * @throws TypeMismatchException */
Array.prototype.swap = function(iIndex1, iIndex2) {
try { var vError = null; var iArrayLength = this.length; var iNumArguments = arguments.length; if (iNumArguments != 2) { throw vError = new IllegalArgumentException("Array.swap", 2, iNumArguments); } if ((typeof iIndex1 != "number") || (iIndex1.toString().indexOf(".") != -1)) { throw vError = new TypeMismatchException("Array.swap", "integer", typeof iIndex1); } if ((typeof iIndex2 != "number") || (iIndex2.toString().indexOf(".") != -1)) { throw vError = new TypeMismatchException("Array.swap", "integer", typeof iIndex2); } if ((iIndex1 < 0) || (iIndex1 >= iArrayLength)) { throw vError = new ArrayIndexOutOfBoundsException("Array.swap", iIndex1, iArrayLength); } if ((iIndex2 < 0) || (iIndex2 >= iArrayLength)) { throw vError = new ArrayIndexOutOfBoundsException("Array.swap", iIndex2, iArrayLength); } var vTempValue = this[iIndex1]; this[iIndex1] = this[iIndex2]; this[iIndex2] = vTempValue; } catch (vError) { if (vError instanceof Error) { vError.handleError(); } } finally { return vError ? null : this; }
}
/**
* Calculates and returns the unbiased variance of all array members or of a * subset of array members (if the optional start and length arguments are * specified). * * @summary unbiased variance * @author Stuart Wigley * @author Randolph Fielding * @version 1.4, 08/08/03 * @interfaceArray.variance()
* @interfaceArray.variance(iStart)
* @interfaceArray.variance(iStart, iLength)
* @requiresArray.mean(iStart, iLength)
* @param iStart the index of the array member to start at (optional) * @param iLength the number of array members to evaluate beginning at *iStart
(optional) * @return the unbiased variance of all array members or of a * subset of array members * @returnnull
if no array members are numbers * @returnnull
if an exception is encountered * @throws ArrayIndexOutOfBoundsException * @throws IllegalArgumentException * @throws MethodNotAvailableException * @throws TypeMismatchException * @throws UnknownException * @seeArray.mean()
*/
Array.prototype.variance = function() {
try { var vError = null; var iArrayLength = this.length; var iNumArguments = arguments.length; var iStart = 0; var iLength = iArrayLength; if (!("mean" in this)) { throw vError = new MethodNotAvailableException("Array.variance", "Array.mean"); } if (iNumArguments > 2) { throw vError = new IllegalArgumentException("Array.variance", "0, 1 or 2", iNumArguments); } else if (iNumArguments == 2) { iStart = arguments[0]; iLength = arguments[1]; } else if (iNumArguments == 1) { iStart = arguments[0]; iLength -= iStart; } if ((typeof iStart != "number") || (iStart.toString().indexOf(".") != -1)) { throw vError = new TypeMismatchException("Array.variance", "integer", typeof iStart); } if ((typeof iLength != "number") || (iLength.toString().indexOf(".") != -1)) { throw vError = new TypeMismatchException("Array.variance", "integer", typeof iLength); } var iEnd = iStart + iLength; if (iStart < 0) { throw vError = new ArrayIndexOutOfBoundsException("Array.variance", iStart, iArrayLength); } if (iLength <= 0) { throw vError = new ArrayIndexOutOfBoundsException("Array.variance", iLength, iArrayLength); } if (iEnd > iArrayLength) { throw vError = new ArrayIndexOutOfBoundsException("Array.variance", iEnd, iArrayLength); } var fMean = this.mean(iStart, iLength); if (!fMean) { throw vError = new UnknownException("Array.variance"); } var fSum = 0; var iCount = 0; for (var i = iStart; i < iEnd; i++) { if (typeof this[i] == "number") { fSum += Math.pow((this[i] - fMean), 2); iCount++; } } if (iCount == 1) { throw vError = new UnknownException("Array.variance"); } var fVariance = (iCount == 0) ? null : fSum / (iCount - 1); } catch (vError) { if (vError instanceof Error) { vError.handleError(); } } finally { return vError ? null : fVariance; }
}
</script> <script type="text/javascript"> var oTest = new Test(); var oDebug = new Debug(); var aSample = new Array(1, 2, 3, 4, 5, "a", "b", "c", "d", "e"); aSample["hello"] = "hesdllo"; </script> </head> <body>
Starting Array = [1, 2, 3, 4, 5, "a", "b", "c", "d", "e"] | |||
Array.averageDev() |
<input id="averageDev1" name="input" type="text" size="5" /> <input id="averageDev2" name="input" type="text" size="5" /> |
<input id="averageDev" type="button" value="Calculate >" onclick="oTest.evaluateMethod(this, "aSample")" /> | <input id="averageDevResult" name="output" type="text" size="30" readonly="readonly" /> |
Array.changeKeyCase() | <input id="changeKeyCase1" name="input" type="text" size="5" /> | <input id="changeKeyCase" type="button" value="Calculate >" onclick="oTest.evaluateMethod(this, "aSample")" /> | <input id="changeKeyCaseResult" name="output" type="text" size="30" readonly="readonly" /> |
Array.chunk() | <input id="chunk1" name="input" type="text" size="5" /> | <input id="chunk" type="button" value="Calculate >" onclick="oTest.evaluateMethod(this, "aSample")" /> | <input id="chunkResult" name="output" type="text" size="30" readonly="readonly" /> |
Array.count() | <input id="count" type="button" value="Calculate >" onclick="oTest.evaluateMethod(this, "aSample")" /> | <input id="countResult" name="output" type="text" size="30" readonly="readonly" /> | |
Array.covar() |
<input id="covar1" name="input" type="text" size="5" /> <input id="covar2" name="input" type="text" size="5" /> |
<input id="covar" type="button" value="Calculate >" onclick="oTest.evaluateMethod(this, "aSample")" /> | <input id="covarResult" name="output" type="text" size="30" readonly="readonly" /> |
Array.fill() |
<input id="fill1" name="input" type="text" size="5" /> <input id="fill2" name="input" type="text" size="5" /> <input id="fill3" name="input" type="text" size="5" /> |
<input id="fill" type="button" value="Calculate >" onclick="oTest.evaluateMethod(this, "aSample")" /> | <input id="fillResult" name="output" type="text" size="30" readonly="readonly" /> |
Array.max() |
<input id="max1" name="input" type="text" size="5" /> <input id="max2" name="input" type="text" size="5" /> |
<input id="max" type="button" value="Calculate >" onclick="oTest.evaluateMethod(this, "aSample")" /> | <input id="maxResult" name="output" type="text" size="30" readonly="readonly" /> |
Array.mean() |
<input id="mean1" name="input" type="text" size="5" /> <input id="mean2" name="input" type="text" size="5" /> |
<input id="mean" type="button" value="Calculate >" onclick="oTest.evaluateMethod(this, "aSample")" /> | <input id="meanResult" name="output" type="text" size="30" readonly="readonly" /> |
Array.median() |
<input id="median1" name="input" type="text" size="5" /> <input id="median2" name="input" type="text" size="5" /> |
<input id="median" type="button" value="Calculate >" onclick="oTest.evaluateMethod(this, "aSample")" /> | <input id="medianResult" name="output" type="text" size="30" readonly="readonly" /> |
Array.min() |
<input id="min1" name="input" type="text" size="5" /> <input id="min2" name="input" type="text" size="5" /> |
<input id="min" type="button" value="Calculate >" onclick="oTest.evaluateMethod(this, "aSample")" /> | <input id="minResult" name="output" type="text" size="30" readonly="readonly" /> |
Array.product() |
<input id="product1" name="input" type="text" size="5" /> <input id="product2" name="input" type="text" size="5" /> |
<input id="product" type="button" value="Calculate >" onclick="oTest.evaluateMethod(this, "aSample")" /> | <input id="productResult" name="output" type="text" size="30" readonly="readonly" /> |
Array.range() |
<input id="range1" name="input" type="text" size="5" /> <input id="range2" name="input" type="text" size="5" /> |
<input id="range" type="button" value="Calculate >" onclick="oTest.evaluateMethod(this, "aSample")" /> | <input id="rangeResult" name="output" type="text" size="30" readonly="readonly" /> |
Array.standardDev() |
<input id="standardDev1" name="input" type="text" size="5" /> <input id="standardDev2" name="input" type="text" size="5" /> |
<input id="standardDev" type="button" value="Calculate >" onclick="oTest.evaluateMethod(this, "aSample")" /> | <input id="standardDevResult" name="output" type="text" size="30" readonly="readonly" /> |
Array.sum() |
<input id="sum1" name="input" type="text" size="5" /> <input id="sum2" name="input" type="text" size="5" /> |
<input id="sum" type="button" value="Calculate >" onclick="oTest.evaluateMethod(this, "aSample")" /> | <input id="sumResult" name="output" type="text" size="30" readonly="readonly" /> |
Array.swap() |
<input id="swap1" name="input" type="text" size="5" /> <input id="swap2" name="input" type="text" size="5" /> |
<input id="swap" type="button" value="Calculate >" onclick="oTest.evaluateMethod(this, "aSample")" /> | <input id="swapResult" name="output" type="text" size="30" readonly="readonly" /> |
Array.variance() |
<input id="variance1" name="input" type="text" size="5" /> <input id="variance2" name="input" type="text" size="5" /> |
<input id="variance" type="button" value="Calculate >" onclick="oTest.evaluateMethod(this, "aSample")" /> | <input id="varianceResult" name="output" type="text" size="30" readonly="readonly" /> |
</body>
</html>
</source>
Displaying the Contents of an Array
<source lang="html4strict">
<script language="JavaScript1.1" type="text/javascript">
</script>
</source>
Dynamic array
<source lang="html4strict">
<HTML> <HEAD> <META NAME="GENERATOR" Content="Microsoft Visual Studio 6.0"> <TITLE></TITLE> <Script language="JavaScript"> ////////////////////////////////////////////////////// // File: vector.js // // Author: Jason Geissler // // Date: Sept 3, 2003 // // Purpose: To have a dynamic collection instead // of using arrays when the total quantity // is unknown ////////////////////////////////////////////////////// // Vector Constructor -- constructs the object function Vector(inc) {
if (inc == 0) { inc = 100; } /* Properties */ this.data = new Array(inc); this.increment = inc; this.size = 0; /* Methods */ this.getCapacity = getCapacity; this.getSize = getSize; this.isEmpty = isEmpty; this.getLastElement = getLastElement; this.getFirstElement = getFirstElement; this.getElementAt = getElementAt; this.addElement = addElement; this.insertElementAt = insertElementAt; this.removeElementAt = removeElementAt; this.removeAllElements = removeAllElements; this.indexOf = indexOf; this.contains = contains this.resize = resize; this.toString = toString; this.sort = sort; this.trimToSize = trimToSize; this.clone = clone; this.overwriteElementAt;
} // getCapacity() -- returns the number of elements the vector can hold function getCapacity() {
return this.data.length;
} // getSize() -- returns the current size of the vector function getSize() {
return this.size;
} // isEmpty() -- checks to see if the Vector has any elements function isEmpty() {
return this.getSize() == 0;
} // getLastElement() -- returns the last element function getLastElement() {
if (this.data[this.getSize() - 1] != null) { return this.data[this.getSize() - 1]; }
} // getFirstElement() -- returns the first element function getFirstElement() {
if (this.data[0] != null) { return this.data[0]; }
} // getElementAt() -- returns an element at a specified index function getElementAt(i) {
try { return this.data[i]; } catch (e) { return "Exception " + e + " occured when accessing " + i; }
} // addElement() -- adds a element at the end of the Vector function addElement(obj) {
if(this.getSize() == this.data.length) { this.resize(); } this.data[this.size++] = obj;
} // insertElementAt() -- inserts an element at a given position function insertElementAt(obj, index) {
try { if (this.size == this.capacity) { this.resize(); } for (var i=this.getSize(); i > index; i--) { this.data[i] = this.data[i-1]; } this.data[index] = obj; this.size++; } catch (e) { return "Invalid index " + i; }
} // removeElementAt() -- removes an element at a specific index function removeElementAt(index) {
try { var element = this.data[index]; for(var i=index; i<(this.getSize()-1); i++) { this.data[i] = this.data[i+1]; } this.data[getSize()-1] = null; this.size--; return element; } catch(e) { return "Invalid index " + index; }
} // removeAllElements() -- removes all elements in the Vector function removeAllElements() {
this.size = 0; for (var i=0; i<this.data.length; i++) { this.data[i] = null; }
} // indexOf() -- returns the index of a searched element function indexOf(obj) {
for (var i=0; i<this.getSize(); i++) { if (this.data[i] == obj) { return i; } } return -1;
} // contains() -- returns true if the element is in the Vector, otherwise false function contains(obj) {
for (var i=0; i<this.getSize(); i++) { if (this.data[i] == obj) { return true; } } return false;
} // resize() -- increases the size of the Vector function resize() {
newData = new Array(this.data.length + this.increment); for (var i=0; i< this.data.length; i++) { newData[i] = this.data[i]; } this.data = newData;
}
// trimToSize() -- trims the vector down to it"s size function trimToSize() {
var temp = new Array(this.getSize()); for (var i = 0; i < this.getSize(); i++) { temp[i] = this.data[i]; } this.size = temp.length - 1; this.data = temp;
} // sort() - sorts the collection based on a field name - f function sort(f) {
var i, j; var currentValue; var currentObj; var compareObj; var compareValue; for(i=1; i<this.getSize();i++) { currentObj = this.data[i]; currentValue = currentObj[f]; j= i-1; compareObj = this.data[j]; compareValue = compareObj[f]; while(j >=0 && compareValue > currentValue) { this.data[j+1] = this.data[j]; j--; if (j >=0) { compareObj = this.data[j]; compareValue = compareObj[f]; } } this.data[j+1] = currentObj; }
} // clone() -- copies the contents of a Vector to another Vector returning the new Vector. function clone() {
var newVector = new Vector(this.size); for (var i=0; i<this.size; i++) { newVector.addElement(this.data[i]); } return newVector;
} // toString() -- returns a string rep. of the Vector function toString() {
var str = "Vector Object properties:\n" + "Increment: " + this.increment + "\n" + "Size: " + this.size + "\n" + "Elements:\n"; for (var i=0; i<getSize(); i++) { for (var prop in this.data[i]) { var obj = this.data[i]; str += "\tObject." + prop + " = " + obj[prop] + "\n"; } } return str;
} // overwriteElementAt() - overwrites the element with an object at the specific index. function overwriteElementAt(obj, index) {
this.data[index] = obj;
}
////////////////////////////////////////////////////// // File: Matrix.js // // Author: Jason Geissler // // Date: March 9, 2004 // // Purpose: To have a multidimensional dynamic collection instead // of using arrays when the total quantity // is unknown ////////////////////////////////////////////////////// // Matrix() - object constructor function Matrix(h, w) {
/*Properties */ this.height = h; this.width = w; this.rows = new Vector(w); // set up this.rows. for (var r = 0; r < this.height; r++) { var theRow = new Vector(w); for (var c = 0; c < this.width; c++) { theRow.addElement(null); } this.rows.addElement(theRow); } /*Methods*/ this.elementAt = elementAt; this.setElementAt = setElementAt; this.insertRow = insertRow; this.insertColumn = insertColumn; this.removeRowAt = removeRowAt; this.removeColumnAt = removeColumnAt; this.getWidth = getWidth; this.getHeight = getHeight; this.toString = toString;
} // getElementAt() - returns a value from the given row/column. function elementAt(row, col) {
try { var theRow = this.rows.getElementAt(row); return theRow.getElementAt(col); } catch(e) { return "Invalid index"; }
} // setElementAt() - sets a value at a given row/column function setElementAt(value, row, col) {
if (row < 0 || row >= this.height || col < 0 || col >= this.width) { return "Matrix object out of Bounds"; } var theRow = this.rows.getElementAt(row); theRow.insertElementAt(value, col);
} // insertRowAt() - Inserts a blank row at the end. function insertRow() {
try { this.height++; var theRow = new Vector(this.width); for (var r = 0; r < this.width; r++) { theRow.addElement(null); } this.rows.insertElementAt(theRow, this.height-1); } catch (e) { return "Excecption occured " + e; }
} // insertColumnAt() -- Inserts a column at the end. function insertColumn() {
try { this.width++; for (var c=0; c < this.height; c++) { this.rows.getElementAt(c).insertElementAt(null, this.width-1); } } catch (e) { return "Invalid column number"; }
} // removeRowAt() - removes a row at a given index. function removeRowAt(row) {
try { var result = this.rows.getElementAt(row); this.height--; for (var r=row + 1; r <= this.height; r++) { var theRow = this.rows.getElementAt(r); this.rows.insertElementAt(theRow, r-1); this.rows.removeElementAt(r); } return result; } catch (e) { return "Invalid row number"; }
} // removeColumnAt() - removes a given column function removeColumnAt(col) {
try { var result = new Vector(this.height); this.width--; for(var r = 0; r < this.height; r++) { var element = this.rows.getElementAt(r).removeElementAt(col); result.addElement(element); } return result; } catch (e) { return "Invalid column number"; }
} // getWidth() - returns the Matrix width function getWidth() {
return this.width;
} // getHeight() - returns the Matrix height function getHeight() {
return this.height;
} // toString() - returns String data about the Matrix object function toString() {
var s = "Height: " + this.height + " Width: " + this.width + " Rows: " + this.rows; return s;
}
</Script>
<Script language="JavaScript">
/*
elementAt; setElementAt; insertRow; insertColumn; removeRowAt; removeColumnAt; getWidth; getHeight; toString;
- /
var theMatrix = new Matrix(8,8); var counter = 1; for (var i = 0; i < theMatrix.getHeight(); i++) { for (var j = 0; j < theMatrix.getWidth(); j++) { if (counter % 2 == 0) { theMatrix.setElementAt("red", i, j); } else { theMatrix.setElementAt("black", i, j); } counter++; } counter++; }
</Script> </HEAD> <BODY>
Element At</TD></TR>
<Script language="JavaScript"> for (var x = 0; x < theMatrix.getHeight(); x++) {document.write(" | |||||||
</TD>");
} document.write("</TR>"); } document.writeln(""); document.writeln(""); document.writeln("<B>Width: " + theMatrix.getWidth()); document.writeln("Height: " + theMatrix.getHeight()); document.writeln("ToString: " + theMatrix.toString()); </Script> |
Remove Row At</TD></TR>
<Script language="JavaScript"> var removedRow = theMatrix.removeRowAt(2); for (var x = 0; x < theMatrix.getHeight(); x++) {document.write(" | |||||||||
</TD>");
} document.write("</TR>"); } </Script> </Table> </Table>
|