LevSelector.com |
Javascript
On this page: | |||
*
main_sites
* books * examples & references * debugging * objects * image rollovers |
*
misc.examples
break lines, alerts, form, clock, hidden frame, select, no multithreading, regex, hash, reverse, reference, location, caching, colors, java applet <=> script, |
*
add
to favorites
* loan payments * list2list * win2win * radio buttons * formcopy * cookies * date_pickers |
*
String
object
* Math*Number * array * misc_functions * Object |
See more on using Javascript in DHTML on my html/dhtml page
Note (2009): This page was first created in 1999. Today (2009) it is definitely outdated, although still may be useful. Javascript made a lot of progress in the last 10 years. And there is much more information on the web. You can look on wikipedia, or you can search for javascript tutorials or javascript interview questions, or you can search for specific topic, for example: javascript closures, etc. Here are some good pages:
Note (2014): Nowadays you can use javascript both on the server side and on front end, and you can write html5/javascript apps which work in browser and on mobile devices:
Here's your homework:
|
--
It would be nice to be able to make HTML page clever enough to do something meaningful or to interact with the user without running to the server every time. For example, if user has made a mistake filling out the form, the validation can be done using some programming embedded into HTML page. This kind of programming is usually done using Javascript.
The idea of having a script embedded into a static HTML page to add
functionality is very powerful. Many scripting languages were used for
this purpose. The embedded scripts can be interpreted
- either on the side of the web server (Server side Javascript,
ASP, PHP, JSP, etc.),
- or on the client browser (client-side Javascript, JScript,
VBScript, Perlscript, etc.).
Below we will talk about client-side (browser) Javascript.
Javascript is a lightweight interpreted programming language.
It allows to:
- Detect the browser type, access some properties of the browser,
window, and HTML document
- Control (to some extent) elements of the browser window and
document (for example, images, layers, etc.).
- Interact with the user, read and write cookies, interact with
java applets
- Do misc. math. calculations, processing with regular expressions,
- and much more.
Javascript syntax is similar to C, C++ and java. You see similar
if/else statements, for/while loops, && operator, { } blocks,
/* ..*/ and // comments, etc. But there are also many differences:
- JavaScript is an untyped language. Same variable can be a number
or a multi-line text (similar to perl).
- Objects in JavaScript are more like Perl's associative arrays.
Cross-browser pains:
Different versions of browsers on different platforms vary dramatically
in how they support Javascript. Everything is different: object models
of the browsers and documents in them (DOM), and how to access document
elements, event handling, etc. Designing a cross-browser Javascript is
a painful process, because you have to detect the type and version of the
browser and write 2 or more versions of the same code embedded in the same
document. Plus after every change you have to test it on different browsers
and platforms as well.
Main Sites | home - top of the page - |
Dan Steinman's tutorial and API (not updated
after October 1999):
* www.dansteinman.com/dynduo/ - CrossBrowser DHTML Tutorial and API * dansteinman.com */dynduo/en/links.html - Dan's DHTML links */dynapi/js/ - collection of javascripts, *ddart.pe.kr/dhtml/dynduo/ - mirror site Download the tutorial and API: * /downloads/dynduo/dynduo-19991024.zip - tutorial in HTML (local basics and DynLayer API as txt to copy into editor for printing) * /downloads/dynapi/dynapi-19991024.zip - APIs * /downloads/dynduo/pdf/dynduo-19991024.pdf - 123 page printable tutorial See (and download) next generation API here
(frequently updated):
|
* DynamicDrive - very good examples and convenient to use |
* www.brainjar.com - Javascript |
* developer.netscape.com/docs/manuals/communicator/jsguide4
- Netscape's JavaScript Guide
* home.netscape.com/eng/mozilla/3.0/handbook/javascript
- Netscape's JavaScript Handbook
* Inside
DHTML -
* www.ruleweb.com/dhtml/
- Jeff Rule's Dynamic HTML and SMIL Site
* HotScripts.com
-
* Javascripts.com
-
* JavaScript.com
-
* www.scriptsearch.com
-
* www.dhtmlzone.com
-
* www.developer.com
- eathweb
* www.builder.com
- CNET
* www.stars.com
- the Web Developer's Virtual Library -
* WebReference.com
-
* www.WebCoder.com
- JavaScript and Dynamic HTML
* javascript.internet.com/
- The Javascript Source, tons of "cut and paste"
* www.irt.org/articles/script.htm
- Javascript articles
* JavaScript
Standard -
* news://usenet/comp.lang.javascript
- Usenet Javascript newsgroup
* home.earthlink.net/~oxherder/
- The Way of Javascript - A brief JavaScript tutorial inspired by the 12th
century verse of the Zen Patriarch, Kakuan - commenting on this set of
Taoist drawings.
* www.wilsonmar.com/1javascr.htm
- sophisticated processing on the browser using Javascript (see
also XML and DOM - Document Object Model)
* www.irt.org/articles/js211/index.htm
- article on multi-dialogue forms
* developer.netscape.com
JavaScript (on Netscape site)
* rummelplatz.uni-mannheim.de/~skoch/js/script.htm
- JavaScript tutorial
* www.hudziak.com/haznet/
- more JavaScripts
* www.zdnet.com/devhead/resources/scriptlibrary/index.html
- more JavaScripts
* www.javagoodies.com
- Javascript, etc.
* www.w3-tech.com/crash/CrashCourse.html
- crash courses in HTML, Java, JavaScript
More javascript:
*www.thefreesite.com/Free_Java_JavaScript
- free Javascript/ Java
* Javascript
Links
* Javascript
Source
* Earthweb
Javascript
* PageResource
Page
* ServerSide
Javascript
Books | home- top of the page - |
Books:
* Javascript for
the World Wide Web (Visual Quickstart Guide) by Tom Negrino, Dori Smith
- simple intro.
|
Examples & References | home - top of the page - |
* examples
from Javascript : The Definitive Guide - Looking through these examples
is the best way to learn Javascript
* reference_page
from Web Master in a Nutshell - 200 KB of Javascript reference on 1
page!! Excellent!!
* www.dansteinman.com/dynduo/
- read first part (Basics) - best intro into DHTML
Download more examples:
* ftp://ftp.oreilly.com/pub/examples/nutshell/javascript/
* ftp://ftp.oreilly.com/pub/examples/nutshell/dynamic_html/
* ftp://ftp.oreilly.com/examples/misc/jscook/
* ftp://ftp.oreilly.com/examples/misc/designjs/
Debugging | home - top of the page - |
Some debugging tools -added September 2008
Old notes (~2000):
Javascript is very sensitive and sometimes tricky to debug. For example, I found that it doesn't like underscores in the names - so don't use them. For example this:
this.form.t_payee.value // will not work
will not work, but this is OK:
this.form.tpayee.value // OK
A common way to debug javascript is to type "javascript:" in location field of Netscape Communicator to pop-up Netscape Communicator Console.
While debugging, it may be convenient to ouput some information.
You can do this using layers: mem/js_dhtml/show_debug_info.html
Or you can simply print to a small window as shown below:
Debug window:
<html>
<head> <script> var dwin = null; function debug(msg) {
<script>var n = 0;</script>
|
Examples - objects | home - top of the page - |
Working with objects:
function MyClassName (paramA, paramB) {
property1 = "prop1 is read only"; propertyA = paramA; propertyB = paramB; // method pointers:
// methods:
// private methods:
var objMyClass = null;
// accessing private method fails - Netscape quietly
bombs:
|
// Defining Method:
function PrintCard() { document.write("Name: ", this.name, "\n"); document.write("Address: ", this.address, "\n"); } // Defining Object (constructor function):
// Creating Instances of Objects:
// Calling method on an object:
// Extending Objects Dynamically: function my_update() {
// add "Class" variable: Card.pi = 3.14159; // extend instance without touching prototype: tom.myupdate = my_update;
// or extend prototype: Card.prototype.myupdate = my_update;
// Another way to add function to a prototype: Card.prototype.myupdate = function() {
//Now you can call: tom.my_update(); |
Examples - image rollovers | home - top of the page - |
Image rollovers:
// Preload images can be done as a function called from body
onload() event:
imageA = new Image();
// If there are many images - you can preload them in a loop: var images = new Array(10);
// You can make your own preload function for convenience: function preload(imgObj,imgSrc) {
// And call it like this:
// Once images are preloaded - all you have to do to change the image is this: document.images["imageName"].src = imageObject.src // You can wrap this into a function ( call it changeImage())
<A HREF="javascript:void(null)"
|
Misc. examples | home - top of the page - |
Breaking program lines into 2 to keep them short - tested on both IE and Netscape browsers:
<html>
<script> // NOTE: be careful - it is not Perl.
// Another example of the same:
// You can split variable assignment near the
"="
// you can initialize several variables on
one line
// you can split list of function parameters
into several lines
// and split list in for loop
// you can split definition of a long string
using '+'
// you can split long logic in if into several
lines in if() or while()
// you can split new window definition into
several lines.
</script>
|
Alert , confirm & prompt:
<html>
<head> <script> function myalert() { ss = "First " + "line\n" + "Second " + "Line"; alert(ss); } function myconfirm() {
function myprompt() {
</script>
|
Form (with data validation):
<html>
<head> <script> function myvalidate() {
function mysubmit(){
</script>
|
Other ways to submit a form:
use submit button: <input type="submit"
value"click me">
or image as a button: <input type="image"
src="mybutton.gif">
To do data validation in these cases, you will have to add onsubmit
handler into the <form> tag.
<form name="form1" method="POST" action="some_action"
onsubmit="mysubmit();return false;">
or like this:
<form name="form1" method="POST" action="some_action"
onsubmit="mysubmit2();">
where
function mysubmit2(){
// some data validation here
if (everything_OK) return true else return
false;
}
Digital clock in status line:
<html>
<head> <script> var timeout_id = null; // This will be used to hide clock function show_clock() {
function hide_clock() {
</script>
|
Hidden frameset (to store some javascript functions and objects):
<html><head><title>some title</title></head>
<frameset name="my_top" rows="0,160,*" frameborder="1" border="1"> <frameset name="my_hidden_frameset" COLS="0,0" frameborder="0" border="0" noresize scrolling="NO"> <frame name="my_hidden_frame1" src="my_hidden_frame1.pl" frameborder="0" border="0" scrolling="NO" noresize> <frame name="my_hidden_frame2" src="my_hidden_frame2.pl" frameborder="0" border="0" scrolling="NO" noresize> </frameset> <frame name="my_head" src="my_head.pl" frameborder="0" border="0" scrolling="NO"> <frame name="my_main" src="my_main.pl" frameborder="1" border="1" scrolling="YES"> </frameset> <noframes> Your browser cannot display frames. </noframes> </html> frame addressing using frame name:
But if internal frameset (f2) is loaded into a frame of an external
frameset (f1), then there are 2 separate frame arrays, and addressing should
go like this:
If your frameset may be called from another frameset, then "top" will
not be your "top" - but the one of the caller frameset. Then you
can use "parent" instead of "top". For example, to address hidden
frame from "my_main" frame you would do something like this:
|
Select onChange handling:
<select name="subject"
onChange="javascript:top.window.frames['my_main_frame'].location = this.options[this.selectedIndex].value"> <option value="main_summary.html" SELECTED>Summary</option> <option value="main_positions.html">Positions</option> </select> |
What if you press a button which started a javascript function (via
onClick event processing) - and while this function is working - you press
another button (or the same button) which similarly should call a function.
Will this function run simultaneously with the first one? Or it will wait
until the first one finishes?
The answer: the 2nd function will wait. here is a test page that demonstrates this. If you want to emulate parallel execution - your function can use setTimeout() to call itself after a delay, during which delay another function (or same function) have a chance to execute. |
Regular Expressions:
function check(num){ // checks if all are digits
var str=num.value var re=/\D+/g if (re.test(str)|| (str=='')){ // do something return } flag_calculate=1 } function commafy(num){ // adds "," in front of each
3 digits
|
Hash:
function dosave () {
//validate var result; var t; // text var m = "Duplicate nicknames are not permitted.\\n Please edit your nickname entries and resubmit this form. "; for (i = 2; i < document.forms.mainForm.elements.length; i++) { t = document.forms.mainForm.elements[i].value; t = t.replace(/\s/g, '_'); eval("if (hash." + t + "== 1) {alert('" + m + "'); result = false} else {hash." + t + " = '1'}"); } if (result != false) { document.forms.mainForm.submit(); } } |
Reverse the string:
var mystring = 'word1 word2';
var myregexp = /\s/ ; // or you can make myregexp='' to split after every char var newArray = mystring.split(myregexp); newArray.reverse(); var my_out_string = unescape(newArray.join('')); |
Value and reference:
var xmas1 = new Date(96, 11, 25);
var xmas2 = xmas; // Both variables now refer to the same object value. xmas2.setDate(21); // we change this object using 2nd ref. xmas1.getDate(); // Returns 21, not the original value of 25. var xmas3 = new Date(96, 11, 25); (xmas1 == xmas2) // Evaluates to true (xmas1 != xmas3) // Evaluates to true. 2 DIFFERENT objects contain the same date. // passing arrays to functions: they passed by copy of a reference as
objects
// Strings compared by value:
|
Location, Links & Anchors:
parent.frames[0].history.back();
parent.frames[0].history.forward(); parent.frames[0].location = "http://www.yahoo.com"; var ss = parent.frames[0].location.href; d= window.document;
var text;
if (ns4) text = a.text;
|
When using "location", how you can make sure that the browser will not use the cached version?
The solution which I use is to tag the url with a dummy parameter with
the date in it - thus tricking the brower into thinking that you are requesting
a different page.
// ------------------------------- var pageLink ='some_domain/cgi-bin/some_script.cgi?key1=value1&key2=value2'; // here it goes var today = new Date(); var ms = today.getTime(); // time in ms var cc = '&'; // use '?' if this will be the first parameter pageLink += cc + 'ms=' + ms; // I add this parameter to force reload of the page some_window.location.href = pageLink ; // some_window.location.href = pageLink + '&ms=' + (new Date()).getTime(); some_window.focus() ; // ------------------------------- You may tag this way any kind of a URL (even static html pages). Other methods, which not always work or desirable:
- Use javascript location.reload(true) command - doesn't necessarily work |
Colors:
function setcolor(w) {
var r = (Math.random() * 256).toString(16); var g = (Math.random() * 256).toString(16); var b = (Math.random() * 256).toString(16); var colorString = "#" + r + g + b; w.document.bgColor = colorString; setTimeout('setcolor(' + w.name + ')', 1000); } |
Java Applets:
// In both browsers (IE & NS) javascript can call public methods
in java applet.
// The method can accept and return numbers, strings and boolean values // (as parameters and return values). var s1 = document.applets["myapplet"].public_java_method(p1,p2,...);
// where <applet code="Applet1.class" width=300 height=300 name="myapplet">...</applet> In Netscape browser you can also pass back and forth objects
|
Add to favorites | home - top of the page - |
Instruction to add the page to favorites
var msg = '';
if ((navigator.appName == "Microsoft Internet Explorer") && (parseInt(navigator.appVersion) >= 4)) { var url="http://www.yourdomain.com"; var title="Your Label"; var msg = '<A HREF="javascript:window.external.AddFavorite(url,title);" ' + 'onMouseOver=" window.status=' + "'Add this site to your favorites!'; return true " + '"onMouseOut=" window.status=' + "' '; return true " + '">Click on this <font color="#993399">link</font> ' + 'to add this web page to your favourites - it means you can come here more easily in future.</a>'; } else { var msg = "Press CTRL and D at the same time now. " +"That will add this web page to your bookmarks - it means you can come here more easily in future"; } document.write(msg); |
Here it is actually working: (text below should be different in IE and Netscape)
Loan Payments example | home - top of the page - |
Loan Payments Calculator: running example
<form name="loandata">
<table> <tr><td colspan=3><big><b>Enter Loan Information:</b></big></td></tr> <tr><td>1)</td><td>Amount of the loan (any currency):</td> <td><input type=text NAME=principal SIZE=12 onChange="calculate()"></td> </tr> <tr><td>2)</td><td>Annual percentage rate of interest:</td> <td><input type=text NAME=interest SIZE=12 onChange="calculate()"></td> </tr> <tr><td>3)</td><td>Repayment period in years:</td> <td><input type=text NAME=years SIZE=12 onChange="calculate()"></td> </tr> <tr><TD COLSPAN=3>
<script> function round(x) { return Math.round(x*100)/100; } function calculate() {
var x = Math.pow(1 + interest, payments);
if (!isNaN(monthly) &&
document.loandata.payment.value
= round(monthly);
</script> |
List to List | home - top of the page - |
Copy selected items between 2 lists:
<html><head><script>
// ------------------------------------
// ------------------------------------
// ------------------------------------
// --------------------------------------
if( exist ) continue; var newOption =
if (toSort) {
} // for cycle removeItems(fromList); // remove selected items from the fromList
}
// note about creating new options and assigning
them values/text in Internet Explorer:
// Note about removing options from select
lists:
</script></head><body>
<table cellpadding=10><tr> <td>
|
Sorting a list of options in a select box:
// ------------------------------------
// ------------------------------------ function compare(aText, bText) { i = 0; aString = aText.toString(); aString.toLowerCase(); bString = bText.toString(); bString.toLowerCase(); if (aString < bString) { return -1; } else if (aString > bString) { return 1; } return 0; } // ------------------------------------
for (var i=0;i<mylist.options.length;i++)
copyOption.sort(function(a,b) { return compare(a[0],b[0]); }); for (var i=mylist.options.length-1; i>-1; i--)
for (var i=0; i<copyOption.length; i++) {
|
Win2win example | home - top of the page - |
Win 2 Win Examples:
Open Window:
<script>
NS4 = (document.layers) ? 1 : 0; IE4 = (document.all) ? 1 : 0; var menuWindow
<style>
|
Update Opener from popup menu:
<html><head><title>some info</title>
<script language="JavaScript"> function updateParent(newURL) { opener.document.location=newURL; self.close() } </script> </head> <body><p><p> Click <a href="javascript:updateParent('http://www.google.com')">here</a> to change main window to Google<br> </body></html> |
Win2win:
<html>
<head> <title> some </title> <script language="JavaScript"> var newWindow function makeWindow(){ newWindow=window.open("","newWin","toolbar=yes,scrollbars=yes,resizable=yes,height=200,width=200") var str="<html><head><title>small window</title>" str+="<script language='JavaScript'>" str+="function updateParent(newURL) { opener.document.location=newURL; self.close() }" str+="<\/script><\/head>" str+="<body>Type text and press the button to send text back to opener<p>" str+="<form onsubmit = 'return false'>" str+="<input type='text' name='info' value=''><br>" str+="<input type='button' value='send info' onClick=" str+="'self.opener.document.forms[0].result.value=this.form.info.value'>" str+="<input type='button' value='close window' onClick=" str+="'self.close()'><br>" str+="<A HREF = \"javascript:updateParent('http://www.yahoo.com')\">goto yahoo and close menu</A><br>" str+="</form></body></html>" newWindow.document.write(str) newWindow.document.close() } </script> </head> <body><p> Sample application showing how to exchange data between 2 windows<p> <form onsubmit = 'return false'> <input type="button" value="Make new window" onClick="makeWindow()"><p> <input type="text" name="result" value=""><br> <input type='button' value='send info' onClick='newWindow.document.forms[0].info.value=this.form.result.value'> </form> </body> </html> |
Radio Buttons Example | home - top of the page - |
Radio Buttons Example:
<html><head><script>
// ------------------------------------ function myshow(ff) { var ss = ""; for (var ii=0 ; ii< ff.group1.length ; ii++) {
</script></head><body bgColor=#FFFFFF>
<br>
<br><a href='javascript:myshow(this.form)'>show</a>
|
Formcopy function example | home - top of the page - |
Form Copy function example:
<script>
function formcopy(f1,f2) {
|
Cookies | home - top of the page - |
A cookie is information that a Web site puts on your hard disk so that
it can remember something about you at a later time.
*
www.LevSelector.com/mem/perl_cgi/cookie.html
- short Perl/Javascript/Java examples
*
do search for cookielib
on search engines ( www.google.com/search?q=cookielib
) - Matt's Script Archive: HTTP Cookie Library.
*
www.zdnet.com/devhead/resources/scriptlibrary/javascript/cookies.html
-
*
www.hidaho.com/cookies/cookie.txt
-
*
www.cookiecentral.com/
-
*
www.worldwidemart.com/scripts/cookielib.shtml
-
*
home.netscape.com/newsref/std/cookie_spec.html
-
*
www.netscapeworld.com/netscapeworld/nw-07-1996/nw-07-cookies.html
-
Date pickers | home - top of the page - |
There are many examples of javascript date pickers:
*
http://www.google.com/search?q=javascript+date+picker
-
*
http://javascript.internet.com/calendars/popup-date-picker.html-
*
http://www.softricks.com/js/Calendar/Calendar.html
-
*
http://www.softricks.com/js/Calendar/tutorial.html
-
*
http://www.softricks.com/js/Calendar/faqs.html
-
*
http://html_help4u.tripod.com/datepick.html
-
*
http://uts.cc.utexas.edu/~esuez/cal5.html
-
*
http://www.siteexperts.com/tips/elements/ts29/page1.asp
-
String | home - top of the page - |
String Object and string datatype are not the same - but in most cases JavaScript converts between them automatically. For example, when you invoke a String object method on a string value, JavaScript converts that value to a temporary String object, allowing the method to be invoked.
Properties - only one - length:
length | The number of characters in the string.
For any string s, the index of the last character is s.length-1. |
Methods:
anchor() | Returns a copy of the string, enclosed within <a name="name"> and </a> HTML tags. |
big() | Returns a copy of the string, enclosed between <big> and </big> HTML tags. |
blink() | Returns a copy of the string, enclosed between <blink> and </blink> HTML tags. |
bold() | Returns a copy of the string, enclosed between <b> and </b> HTML tags. |
charAt() | string.charAt(n) //n is the index of the character
to be returned
Extracts the n-th character from a string. The first character of the string is numbered 0. If n is not between 0 and string.length-1, then this method returns an empty string. Note that JavaScript does not have a character datatype that is distinct from the string type, so the returned character is a string of length 1. |
fixed() | Returns a copy of the string, enclosed between <tt> and </tt> HTML tags. |
fontcolor() | string.fontcolor(color)
Returns a copy of the string, enclosed between <font color="color"> and </font> HTML tags. The color argument is a string specifying the color name or value to be used as the value of the color attribute in the <font> HTML tag. Colors are specified either as one of the standard color names recognized by JavaScript, or as red, green, and blue color values, expressed as six hexadecimal digits (RRGGBB). |
fontsize() | string.fontsize(size)
Returns a copy of the string, enclosed between <font size="size"> and </font> HTML tags. The size argument is an integer between 1 and 7 or a string that begins with a + or - sign followed by a digit between 1 and 7. If an integer is specified, it is an absolute font size specification. If a string is specified, the font specification is relative to the <basefont> size. |
indexOf() | string.indexOf(substring)
string.indexOf(substring, start) Searches the string for an occurrence of substring. The search begins at position start within string, or at the beginning if no start is specified. start is an integer between 0 and string.length-1. Returns the position of the first occurrence of substring after the start position, or -1 if no occurrence is found. |
italics() | Returns a copy of the string, enclosed between <i> and </i> HTML tags. |
lastIndexOf() | string.lastIndex(substring)
string.lastIndex(substring, start) Searches the string backwards for an occurrence of substring. The search begins at position start within string, or at the end, if no start is specified. start is an integer between 0 and string.length-1. Returns the position of the first occurrence of substring before the start position, or -1 if no occurrence is found. |
link() | string.link(href)
Returns a copy of the string, enclosed between <a href="size"> and </a> HTML tags. href specifies the URL target of the hypertext link that is to be added to the string. This string argument specifies the value of the HREF attribute of the <a> HTML tag. |
small() | Returns a copy of the string, enclosed between <small> and </small> HTML tags. |
split() | string.split()
string.split(delimiter) Converts a string to an array of strings, using a specified delimiter character/string at which the string will be split. If no delimiter is specified, then the returned array has only one element, the string itself. Note that the String.split() method is the inverse of the Array.join() method. |
strike() | Returns a copy of the string, enclosed within <strike> and </strike> HTML tags. |
sub() | Returns a copy of the string, enclosed within <sub> and </sub> HTML tags. |
substring() | string.substring(from, to)
Extracts a substring of a string. from is a value between 0 and string.length-1. to is an optional integer that is one greater than the position within string of the last character of the desired substring. to must be between 1 and string.length. The character at position from is included in the substring, while the character at position to is not. The returned string contains characters copied from positions from to to-1 of string. |
sup() | Returns a copy of the string, enclosed within <sup> and </sup> HTML tags. |
toLowerCase() | Returns a copy of the string, with all characters converted to lowercase. |
toUpperCase() | Returns a copy of the string, with all characters converted to uppercase. |
valueOf() | Returns the string value contained in the String object; Netscape 3.0 and later. See Object.valueOf(). |
Examples of usage:
A number of the String methods are used for creating HTML:
link_text = "My Home Page".bold();
document.write(link_text.link("http://www.djf.com/~david"));
The code above code embeds the following string into the HTML document that is currently being parsed:
<A HREF="http://www.djf.com/~david"><B>My Home Page</B></A>
The following code extracts the 3rd through 5th characters of a string and converts them to upper-case letters:
s.substring(2,5).toUpperCase();
Math object | home - top of the page - |
Math Object is a read-only reference to a placeholder object that contains mathematical functions and constants. Math is itself an object, not a class of objects, so its constants and methods are invoked directly through it. Math is actually a global property of the Window object, and as such, is usually referred to as Math, rather than as window.Math. See also Number
There are functions and constants:
Math.constant
Math.function()
area = radius * radius * Math.PI;
y = Math.sin(x);
Constants:
Math.E | e = the base of natural logarithms |
Math.LN2 | The natural logarithm of 2 |
Math.LN10 | The natural logarithm of 10 |
Math.LOG10E | The base-10 logarithm of e |
Math.LOG2E | The base-2 logarithm of $e$ |
Math.PI | The constant pi |
Math.SQRT2 | The square-root of 2 |
Math.SQRT1_2 | The reciprocal of the square-root of 2 |
Methods (Functions):
abs | Math.abs(x) // x is any numeric value or expression | Computes an absolute value. |
acos | Math.acos(x) // x is a numeric value or expression between -1.0 and 1.0 radians | Computes an arc cosine (inverse cosine). Return value is between 0 and pi radians. |
asin | Math.asin(x) // x is a numeric value or expression between -1.0 and 1.0 radians | Computes an arc sine (inverse sine). The return value is between -pi/2 and pi/2 radians. |
atan | Math.atan(x) //x is any numeric value or expression | Computes an arc tangent (inverse tangent) in radians. The return value is between -pi/2 and pi/2 radians. |
atan2 | Math.atan2(x, y) // x, y are the coordinates of the point | Computes the counter-clockwise angle from the positive X axis to a point (x, y). Performs half of the conversion between Cartesian coordinates and polar coordinates; computes and returns the angle theta of an (x, y) point. |
ceil | Math.ceil(x) // x is any number or numeric expression | Rounds a number up to the closest integer (i.e., computes the ceiling function); negative numbers are rounded up to 0. |
cos | Math.cos(x) // x is any number or numeric expression, in radians | Computes a cosine; the return value will be between -1.0 and 1.0 radians. |
exp | Math.exp(x) // x is a number or numeric expression to be used as exponent | Computes an exponent of $e$. |
floor | Math.floor(x) // x is any numeric value or expression | Rounds a number down to the closest integer (i.e., computes the floor function); negative numbers are rounded to be more negative. |
log | Math.log(x) // x is any numeric value or expression greater than 0 | Computes a natural logarithm. |
max | Math.max(a, b) // a, b are any two numeric values or expressions | Returns the larger of two values. |
min | Math.min(a, b) // a, b are any two numeric values or expressions | Returns the smaller of two values. |
pow | Math.pow(x, y) | Computes $x sup y$. (Raises its first argument to the power of its second argument and returns the result.) |
random | var r = (Math.random() * 256).toString(16); | Computes a random number; |
round | Math.round(x) // x is any numeric value or expression | Rounds to the closest integer |
sin | Math.sin(x) // x is an angle, in radians | Computes a sine. |
sqrt | Math.sqrt(x) // x is any numeric value or expression greater than or equal to 0 | Computes a squareroot. |
tan | Math.tan(x) | Computes a tangent. |
atan | Math.atan(x) // x is an angle, in radians | Opposite to tan |
Number object | home - top of the page - |
Number Object
Numbers are a basic, primitive data type in JavaScript.
The Number() constructor:
new Number(value)
is actually more commonly used as a placeholder for five useful numeric
constants. Note that these values are properties of the Number() constructor
function itself, not of individual number objects. For example, you use
the MAX_value property as follows:
biggest = Number.MAX_value
not like this:
n = new Number(2);
biggest = n.MAX_value // wrong
Constants:
MAX_value | The largest representable number. |
MIN_value | The smallest (i.e., closest to zero, not most negative) number representable in JavaScript. |
NaN | Special Not-a-Number value. JavaScript prints the Number.NaN value as NaN. Note that the NaN value always compares unequal to any other number, including itself. Thus, you cannot check for the not-a-number value by comparing to Number.NaN. Use the isNaN() function instead. |
NEGATIVE_INFINITY | Special negative infinite value; returned on overflow. JavaScript displays the NEGATIVE_INFINITY value as -Inf. This value behaves mathematically like an infinity. |
POSITIVE_INFINITY | Special infinite value; returned on overflow. JavaScript displays the POSITIVE_INFINITY value as Inf. This value behaves mathematically like an infinity. |
Methods:
toString() | number.toString(radix) // radix is an integer between 2 and 16 | Converts a number to a string, using a specified radix (base). |
By contrast, the toString() method of the Number object is a method of each Number object, not of the Number() constructor function. JavaScript implicitly invokes the Number() constructor to convert the number to a temporary Number object for which the toString() method can be invoked. Thus you can use the toString method with a variable that holds a number, even though that value is not actually an object:
var n = 1234;
var binary_string = n.toString(2);
var hex_string = n.toString(16);
Array object | home - top of the page - |
Array Object
new Array() // with no arguments, length field
is set to 0
new Array(size) // size = number of elements;
sets length
new Array(element0, element1, ..., elementn) // length set to number
of elements
Properties:
length | a = new Array(); // a.length initialized
to 0
b = new Array(10); // b.length initialized to 10 c = new Array("one", "two", "three"); // c.length initialized to 3 c[3] = "four"; // c.length updated to 4 c[10] = "blastoff"; // c.length becomes 11 |
You can also set the value
of the length property to change the size of an array (i.e., truncate elements or add "undefined" ones). |
Example: make multidimensional array as an array of arrays:
<html><head>
<script> arr = new Array([1,2,3], [4,5,6,61,62], [7,8,9]);
ss+="total length: " + arr.length + " elements<br>\n"; for (i=0;i<3;i++) {
ss+="<br>\n";
/*
total length: 3 elements
</script>
|
Methods
join | array.join()
array.join(separator) |
If no separator, the empty string is used. Converts each of the elements of an array to a string, and then concatenates those strings, inserting the specified separator string between the elements. Returns the resulting string. You can split a string up into array elements--with the split() method of the String object. |
reverse | Reverse, in place (i.e., without creating a new array), the order of the elements of an array. | |
sort | array.sort()
array.sort(orderfunc) // orderfunc - optional comparison function |
With no arguments, sorts by asc; You may supply a function that compares two values (a & b) and returns a number (-1, 0 or 1) indicating if a is less, eq. or greater than b. |
Some functions | home - top of the page - |
Some Functions
escape( ) | escape("Hello World!"); // returns Hello%20World% | returns a new string that contains an encoded version of s to allow transmission of data. Commonly used to encode cookie values. See also String, unescape(). |
eval() | eval(code) | Executes Javascript code in its string argument. Returns the value
of the last expression in code that it evaluates. |
isNaN( ) | isNaN(x) | Tests whether an argument (x) is "not a number". Commonly
used to test the results of parseFloat() and parseInt() to see if they represent legal numbers, or to check for arithmetic errors, such as division by zero. |
parseFloat( ) | parseFloat(s) // s is the string to be parsed and coverted to a number | Parses and returns the first number that occurs in s (i.e., converts a string to a number). Parsing stops, and the value is returned, when parseFloat() encounters a character in s that is not a valid part of the number (i.e., a sign, a digit, decimal point, exponent, etc.). If s does not begin with a number that parseInt() can parse, then the function returns NaN. |
parseInt( ) | parseInt(s)
parseInt(s, radix) //s is the string to be parsed //radix is the integer base of the number to be parsed // radix can be any value between 2 and 36. |
Parses and returns the first number that occurs in the string s (i.e.,
it converts a string to an integer). Parsing stops, and the value is returned,
when parseInt() encounters a character in s that is not a valid numeral
for the specified radix. If s does not begin with a number that parseInt()
can parse, then the function returns NaN.
If radix is 0, or if it is not specified, parseInt() tries to determine the radix of the number from s. If s begins with 0x, then parseInt() parses the remainder of s as a hexadecimal number. If s begins with a 0, then parseInt() parses the number in octal. Otherwise, if s begins with a digit 1 through 9, then parseInt() parses it as a decimal number. |
unescape( ) | unescape ('Hello%20World%21')
// returns Hello World! |
decodes a string encoded with escape() and returns the decoded copy.
unescape() decodes s by finding and replacing character sequences of the form %xx, where xx is two hexadecimal digits. |
Object Object | home - top of the page - |
Object Object - serves as the "superclass" for all other JavaScript
objects, and therefore methods of the Object object are also methods of
all other object types. The behavior of the Object object is also shared
by all other object types. When an Object object is newly created, it has
no properties defined; you can add a property definition to an object
simply by assigning a value to the property.
Objects can
also be used
as associative arrays.
new Object();
new Object(value);
Methods:
assign() | object.assign(value) // value is the value to be assigned | If defined, used to implement the JavaScript assignment operator (=). |
eval() | eval(code)
window.eval(code) |
Evaluates a string of JavaScript code in the context of the given object. |
toString() | . | If defined, used to convert an object to a string. |
valueOf() | . | Returns the primitive value of the object, if any. For objects of type Object, this method simply returns the object itself. For other object types, such as Number and Boolean, this method returns the primitive value associated with the object. |
Example:
Defining the toString(), method, and also the less frequently used
assign() and valueOf() methods of an object, is most efficiently done in
a
constructor method for your object type, or with the prototype object
of your object.
// define a constructor for the Complex object type
function Complex(x,y) { this.x =
x; this.y = y; }
// give it a toString() method
Complex.prototype.toString = new
Function("return '{' + this.x + ',' + this.y + '}';");
// Create an object of this new Complex type
c = new Complex(2, 2);
// Convert the object to a string, implicitly invoking the toString()
method, and display the string.
alert("c = " + c);
---------------------------------------