JS set of functions
• Strings (String)
1. Disclaimer
var myString = new String ("Every Good boy does fine.");
var myString = "Every Good boy does fine.";
2. String connection
var myString = "Every" + "good boy" + "does fine.";
var myString = "every"; MyString + = "Good boy does fine.";
3. Intercepting strings
//intercept the character beginning with the 6th bit
var myString = "Every Good boy does fine.";
var section = myString. substring (6);The result: "Good boy does fine."
//intercept the No. 0 digit from the beginning to the 10th digit
var myString = "Every Good boy does fine.";
var section = myString.substring (0,10); Result: "Every good"
//intercept characters from 11th to 6th place
var myString = "Every Good boy does fine.";
var section =Mystring.slice (11,-6); Result: "Boy does"
//4-length characters starting from the 6th bit
var myString = "Every Good boy does fine.";
var section = Mystring.substr (6,4); Result: "Good"
4. Convert case
var myString = "Hello";
var lcstring = Mystring.tolowercase (); Result: "Hello"
var ucstring = Mystring.touppercase (); Result: "HELLO"
5. String comparisons
var astring = "hello!";
var bstring = new String ("hello!");
if (astring = = "Hello!") {}//Result: true
if (astring = = bstring) {}//Result: true
if (astring = = = bstring) {}//Result: False (two objects are different, although their values are the same)
6. Retrieving strings
var myString = "Hello everybody.";
If the retrieval does not return to 1, the retrieved words are returned in the starting position of the string.
IfMystring.indexof ("every") >-1) {}//Result: true
7. Find Replacement strings
var myString = "I is your father.";
var result =Mystring.replace ("is", "AM"); Result: "I am your father."
8. Special characters:
\b: Back character \ t: Horizontal tab
\ n: NewLine character \v: Vertical tab
\f: page break \ r: Carriage return
\ ": double quotation mark \ ': Single quote
\ \: Anti-skew bar
9. Converting characters to Unicode encoding
var myString = "Hello";
var code = mystring.charcodeat (3); Returns the Unicode encoding for "L" (integer type)
var char = String.fromCharCode (66); Returns the Unicode 66 character
10. Converting a string into a URL encoding
var myString = "Hello all";
var code = encodeURI (myString); Result: "Hello%20all"
var str = decodeURI (code); Result: "Hello all"
The corresponding also: encodeURIComponent () decodeuricomponent ()
11. Convert a string to base64 encoding
Base64Encode () Base64decode () use ibid.
//-----------------------------------------------------------------------
• Digital type (number)
1. Disclaimer
var i = 1;
var i = new number (1);
2. Conversion between strings and numbers
var i = 1;
var str = i.tostring (); Result: "1"
var str = new String (i); Result: "1"
i = parseint (str); Results: 1
i = parsefloat (str); Results: 1.0
Note: Parseint,parsefloat will convert a string similar to "32G" to 32.
3determine if the number is valid
var i = 123; var str = "string";
if (typeof i = = "number") {}//true
Some methods (for example: Parseint,parsefloat) return a special value Nan (not a number)
Notice in the 2nd [note] that this method is not entirely suitable for judging whether a string is a numeric type!!
i = parseint (str);
if (IsNaN (i)) {}
4. Comparison of digital type
This knowledge is the same as [string comparison]
5. Decimal to Integer
var f = 1.5;
var i = Math.Round (f); Results: 2 (rounded)
var i = Math.ceil (f); Result: 2 (returns the smallest integer greater than f)
var i = Math.floor (f); Result: 1 (returns the largest integer less than f)
6. Format the display of numbers
var i = 3.14159;
Floating-point numbers formatted as two decimal places
var str = i.tofixed (2); Result: "3.14"
Floating-point number formatted as a five-digit number (five digits from left to right, not enough to fill 0)
var str = i.toprecision (5); Result: "3.1415"
Conversion of 7.X binary numbers
I don't know-.-
var i = parseint ("0x1f", 16);
var i = parseint (i,10);
var i = parseint ("11010011", 2);
8. Random number
Returns any decimal between 0-1
var rnd = Math.random ();
Returns any integer between 0-n (not including N)
var rnd = Math.floor (Math.random () * N)
//-----------------------------------------------------------------------
· Math Object
1. Math.Abs (num): Returns the absolute value of num
2. Math.acos (num): Returns the inverse cosine value of num
3. Math.asin (num): Returns the inverse sine value of num
4. Math.atan (num): Returns the inverse tangent value of num
5. Math.atan2 (Y,X): Returns the inverse tangent value of the quotient of y divided by X
6. Math.ceil (num): Returns the smallest integer greater than num
7. Math.Cos (num): Returns the cosine value of num
8. Math.exp (x): Returns the number of X-Powers at the base of the natural number
9. Math.floor (num): Returns the largest integer less than num
10.math.log (num): Returns the natural logarithm of num
11.math.max (NUM1,NUM2): Returns the larger of NUM1 and num2
12.math.min (NUM1,NUM2): Returns the smaller of NUM1 and num2
13.math.pow (x, y): Returns the value of the Y-square of X
14.math.random (): Returns a random number from 0 to 1
15.math.round (num): Returns the value after Num is rounded
16.math.sin (num): Returns the sinusoidal value of num
17.MATH.SQRT (num): Returns the square root of num
18.math.tan (num): Returns the tangent value of num
19.MATH.E: Natural number (2.718281828459045)
The natural logarithm of the 20.math.ln2:2 (0.6931471805599453)
The natural logarithm of the 21.math.ln10:10 (2.302585092994046)
22.math.log2e:log 2 is the base natural number (1.4426950408889634)
23.math.log10e:log 10 is the base natural number (0.4342944819032518)
24.math.pi: π (3.141592653589793)
Square root of 25.MATH.SQRT1_2:1/2 (0.7071067811865476)
Square root of 26.math.sqrt2:2 (1.4142135623730951)
//-----------------------------------------------------------------------
• DateTime (date)
1. Disclaimer
var mydate = new Date (); System Current Time
var mydate = new Date (yyyy, MM, DD, hh, MM, ss);
var mydate = new Date (yyyy, MM, DD);
var mydate = new Date ("MonthName dd, yyyy hh:mm:ss");
var mydate = new Date ("MonthName dd, yyyy");
var mydate = new Date (epochmilliseconds);
2. Get part of the time
var mydate = new Date ();
Mydate.getyear (); Get Current year (2-bit)
Mydate.getfullyear (); Get the full year (4-bit, 1970-????)
Mydate.getmonth (); Get the current month (0-11, 0 for January)
Mydate.getdate (); Get current day (1-31)
Mydate.getday (); Get Current week x (0-6, 0 for Sunday)
Mydate.gettime (); Gets the current time (the number of milliseconds since 1970.1.1)
Mydate.gethours (); Get current number of hours (0-23)
Mydate.getminutes (); Gets the current number of minutes (0-59)
Mydate.getseconds (); Gets the current number of seconds (0-59)
Mydate.getmilliseconds (); Gets the current number of milliseconds (0-999)
Mydate.tolocaledatestring (); Get Current date
Mydate.tolocaletimestring (); Get current time
Mydate.tolocalestring (); Get Date and time
3. Calculate the time before or in the future
var mydate = new Date ();
Mydate.setdate (Mydate.getdate () + 10); Current Time plus 10 days
Similar methods are basically the same, starting with set, specific reference to the 2nd
4. Calculate an offset of two dates
var i = Daysbetween (begindate,enddate); Return days
var i = Begindate.gettimezoneoffset (endDate); Returns the number of minutes
5. Check validity date
Checkdate () only allow dates in either "mm-dd-yyyy" or "mm/dd/yyyy" format
if (Checkdate ("2006-01-01")) {}
Regular Expressions (self-written check yyyy-mm-dd, Yy-mm-dd, YYYY/MM/DD, yy/mm/dd four kinds)
var r =/^ (\d{2}|\d{4}) [\/-]\d{1,2}[\/-]\d{1,2}$/;
if (R.test (myString)) {}
//-----------------------------------------------------------------------
• Arrays (array)
1. Disclaimer
var arr = new Array (); Declares an empty array
var arr = new Array (10); Declares an array of 10 lengths
var arr = new Array ("Alice", "Fred", "Jean"); Initializing an array with values
var arr = ["Alice", "Fred", "Jean"]; Initializing an array with values
var arr = [["A", "B", "C"][1,2,3]]; Declaring a two (multi)-dimensional array
2. Access to arrays
Arr[0] = "123"; Assign value
var str = arr[0]; Get
Arr[0][0] = "123"; Multidimensional array Assignment
3. Conversion between arrays and strings
var arr = ["A", "B", "C", "D"]; Statement
//arrays are converted into strings by delimiter
var str = arr. Join ("|"); Result: "a| b| c| D
//String cut array
arr =Str.split ("|");
4. Iterating through an array
for (var i=0; i<arr.length; i++) {alert (arr[i]);}
5. Sorting
var arr = [12,15,8,9];
Arr.sort (); Results: 8 9 12 15
6. Grouping and decomposing arrays
var arr1 = ["A", "B", "C", "D"];
var arr2 = ["1", "2", "3", "4"];
Award two array groups to synthesize a new array
var arr = Arr1.concat (ARR2); Results: ["A", "B", "C", "D", "1", "2", "3", "4"]
Cut an array into two arrays (parameter 1: Start index, Parameter 2: Cut length)
var arr3 = Arr.splice (1,3); Results: arr3:["B", "C", "D"] arr["A", "1", "2", "3", "4"]
Cut an array into two arrays and fill in the original array with a new value
var arr4 = Arr.splice (1,3, "AA"); Results: arr4:["B", "C", "D"] arr["A", "AA", "1", "2", "3", "4"]
//-----------------------------------------------------------------------
• Custom Objects
1. Disclaimer:
function MyUser (uid,pwd) {
This.uid = UID;
this.pwd = pwd | | "000000"; Default value
This.show = Showinfo; Method
}
The following function is not a custom object and is a method of customizing the object. Just keep looking.
function Showinfo () {
Alert ("Username:" + this.uid + ", Password:" + this.pwd)
}
2. Instantiation:
var user = new MyUser ("User", "123456");
var user = {uid: "user", pwd: "123456"};
3. Get and set
Alert ("User name is:" + user.uid); Get
User.uid = "NewUser"; Set
User.show (); Call the show () method
//-----------------------------------------------------------------------
• Variable function flow control
1. Variables
var i = 1;
var i = 1, str = "Hello";
2. Functions
function Funname () {
Do something.
}
function Funname (Param1[,paramx]) {
Do something.
}
3. Nesting functions
In some cases, you need to create a function that is unique to the function itself.
function MyFunction () {
Do something.
Privatefunction ();
function Privatefunction () {
Do something.
}
}
4. Anonymous functions
var tmp = function () {alert ("only Test.");}
TMP ();
5. Deferred function calls
var tId = SetTimeout ("Myfun ()", 1000); Delay 1000 milliseconds before calling the Myfun () function
Fucntion Myfun () {
Do something
Cleartimeout (TID); Destroying objects
}
6. Process Control
if (condition) {}
if (condition) {} else{}
if (condition) {} else if (condition) {} else{}
switch (expression) {
Case Vala:statement; Break
Case Valb:statement; Break
Default:statement; Break
}
7. Exception Capture
try{expression} catch (e) {} finally{}
Do not handle any exceptions
Window.onerror = doNothing;
function doNothing () {return true;}
Properties available for exception classes
Description: Exception description (IE,NN)
fileName: Exception page URI (NN)
linenumber: Number of exception rows (NN)
Message: Exception description (IE,NN)
Name: Error type (IE,NN)
Number : Error code (IE)
Error message (compatible with all browsers)
try{}
catch (e) {
var msg = (e.message)? e.message:e.description;
Alert (msg);
}
8. Speed up execution of scripts
-Avoid using the eval () function
-Avoid using with keyword
-Minimizes duplicate expression assignments
-Use an index to find an array in a larger object
-Reduced use of document.write ()
//-----------------------------------------------------------------------
• Browser features (navigator)
1. Browser name
IE: "Microsoft Internet Explorer"
NS: "Netscape"
var browsername =navigator.appname;
2. Browser version
Bar Browserversion =navigator.appversion;
3. Client operating system
var Iswin = (navigator.userAgent.indexOf ("Win")! =-1);
var Ismac = (navigator.userAgent.indexOf ("Mac")! =-1);
var Isunix = (navigator.userAgent.indexOf ("X11")! =-1);
4. Determine if an object, method, property is supported
When an object, method, property is undefined, it returns undefined or null, and so on, these special values are false
if (document.images) {}
if (document.getElementById) {}
5. Check the current language of the browser
IfNavigator.userlanguage) {var L = navigator.userLanguage.toUpperCase ();}
6. Check whether the browser supports cookies
Ifnavigator.cookieenabled){ }
//-----------------------------------------------------------------------
• Control the browser window (Windows) "There may be a problem, pending verification】
1. Set the browser size
Window.resizeto (800, 600);//Adjust the browser to 800x600 size
Window.resizeby (50,-10);//change size to increase or decrease window size
2. Adjust the browser's location
Window.moveto (10, 20);//location of the browser to X:10 y:20
Window.moveby (0, 10);//move position in original position (offset)
3. Create a new window
var win = window.open ("about.htm", "Winname", "height=300,width=400");
Parameters
Alwayslowered//Always in the back of other browser windows (NN)
alwaysraised//Always in front of other browser windows (NN)
Channelmode//Is Navigation mode (IE)
Copyhistory//Copy history to the newly opened window (NN)
Dependent//New window closes with the main window that opens it (NN)
Fullscreen//fullscreen mode (none of the related toolbars) (IE)
Location//Whether the address bar is displayed (Nn,ie)
MenuBar//whether the menu bar is displayed (Nn,ie)
ScrollBars//Whether scroll bar is displayed (Nn,ie)
Status//whether to display the State bar (Nn,ie)
Toolbar//Whether the toolbar is displayed (Nn,ie)
Directories//Whether to show the link bar (nn,ie)
TitleBar//Whether to display the title bar (NN)
Hotkeys//Display menu shortcut key (NN)
Innerheight//height of the content area (NN)
Innerwidth//width of the content area (NN)
Resizable//Can be resized (Nn,ie)
Top//Window size (Nn,ie) from the top edge of the desktop
Left//Window size (Nn,ie) away from desktop
Height//width of window (nn,ie)
Width//breadth of browser
4. Communicating with the new window
Win.focus (); Get focus for new window
Win.document.write ("abc"); Working on a new window
Win.document.close (); End Stream Operation
Opener.close ();
5. Mode window
window.showModalDialog ("test.htm", Dialogargs, "param"); Passing objects
Window.showmodelessdialog ("test.htm", MyFunction, "param"); Transfer function
Window.dialogarguments//dialog box accesses objects passed by the parent window
Window.returnvalue//Parent window Gets the value returned by the dialog box
Parameters
Center//Window Center screen
dialogheight//Window height
Dialogwidth//Window width
Dialogtop//window distance from the top margin of the screen
Dialogleft//window distance to the left of the screen
Edge//Border style (Raised|sunken)
Help//Display assistance button
Resizable//Can change the window size
Status//Whether the State bar is displayed
Example
<script>
function OpenDialog (myForm) {
var result = window.showModalDialog ("new.html", MyForm, "center");
}
</script>
<form action= "#" onsubmit= "return false" >
<input type= "text" id= "txtID" >
<input type= "button" id= "Btnchk" value= "Verify the availability of" onclick= "OpenDialog (this.form);" >
</form>
Another page new.html
<script>
window.dialogArguments.btnChk.enabled = false; Set the button in the parent window to not available
Do something to check the Id.
Window.write ("User id:" + window.dialogArguments.txtId.value + "can use!"); Get the value of a text box
</script>
//-----------------------------------------------------------------------
• Management Framework Web page (frames)
1. Create a Framework schema page
<frameset rows= ", *" >
<frame name= "header" src= "header.html" >
<frame name= "main" src= "main.html" >
</frameset>
2. Visit the frames page
Window.frames[i]
window.frames["FrameName"]
Window.framename
window.frames["FrameName"].frames["frameName2"]
parent.frames["FrameName"]
top.frames["FrameName"]
3. Directing a page to a frame
<a href= "new.html" target= "main" >
Location = "new.html";
Parent.frameName.location.href = "new.html";
Top.frameName.location = "new.html";
4. Force no other frame to reference a page
if (top! = self) {
Top.location.href = Location.href;
}
5. Change the size of the frame
Document.framesetName.rows = "50,*";
Document.framesetName.cols = "50,*";
6. Dynamically Create frames page
var frag = document.createdocumentfragment ();
var newframe= document.createelement ("frame");
Newframe.id = "header";
Newframe.name = "header";
Newframe.src= "Header.html"
Frag.appendchild (Newframe);
Newframe = document.createelement ("frame");
Newframe.id = "main";
Newframe.name = "main";
Newframe.src= "Main.html"
Frag.appendchild (Newframe);
document.getElementById ("Masterframeset"). Rows = "50,*";
JS set of functions