javascript Common function summary

  • 2020-07-21 06:40:14
  • OfStack

1. API array


// Define an array  
var pageIds = new Array(); 
pageIds.push('A'); 
 The length of the array  
pageIds.length; 
//shift : Delete the original array 1 Item, and returns the value of the deleted element; Returns if the array is empty undefined 
var a = [1,2,3,4,5]; 
var b = a.shift(); //a : [2,3,4,5] b : 1 
//unshift : Adds a parameter to the beginning of the original array and returns the length of the array  
var a = [1,2,3,4,5]; 
var b = a.unshift(-2,-1); //a : [-2,-1,1,2,3,4,5] b : 7 
// Note: in IE6.0 The return value of the next test is always zero undefined . FF2.0 The following test returns a value of 7 , so the return value of this method is not reliable and is available when the return value is needed splice Use instead of this method.  
//pop : Deletes the original array last 1 Item, and returns the value of the deleted element; Returns if the array is empty undefined 
var a = [1,2,3,4,5]; 
var b = a.pop(); //a : [1,2,3,4] b : 5 
//push : Adds the parameter to the end of the original array and returns the length of the array  
var a = [1,2,3,4,5]; 
var b = a.push(6,7); //a : [1,2,3,4,5,6,7] b : 7 
//concat Returns the 1 A new array is formed by adding parameters to the original array  
var a = [1,2,3,4,5]; 
var b = a.concat(6,7); //a : [1,2,3,4,5] b : [1,2,3,4,5,6,7] 
//splice(start,deleteCount,val1,val2,) From: start Position start to delete deleteCount Item and insert from that location val1,val2, 
var a = [1,2,3,4,5]; 
var b = a.splice(2,2,7,8,9); //a : [1,2,7,8,9,5] b : [3,4] 
var b = a.splice(0,1); // with shift 
a.splice(0,0,-2,-1); var b = a.length; // with unshift 
var b = a.splice(a.length-1,1); // with pop 
a.splice(a.length,0,6,7); var b = a.length; // with push 
//reverse : Reverse order the array  
var a = [1,2,3,4,5]; 
var b = a.reverse(); //a : [5,4,3,2,1] b : [5,4,3,2,1] 
//sort(orderfunction) Sorts the array by the parameter specified  
var a = [1,2,3,4,5]; 
var b = a.sort(); //a : [1,2,3,4,5] b : [1,2,3,4,5] 
//slice(start,end) : Returns a new array of items from the original array that specify the starting and ending subscripts  
var a = [1,2,3,4,5]; 
var b = a.slice(2,5); //a : [1,2,3,4,5] b : [3,4,5] 
//join(separator) : Groups the elements of an array 1 A string of, to separator A comma is the default delimiter for ellipsis  
var a = [1,2,3,4,5]; 
var b = a.join("|"); //a : [1,2,3,4,5] b : "1|2|3|4|5" 

2.dom:


//document Methods:  
getElementById(id) Node  Returns a reference to the specified node  
getElementsByTagName(name) NodeList  Returns a collection of all matched elements in the document  
createElement(name) Node Node 
createTextNode(text) Node  create 1 A plain text node  
ownerDocument Document  Points to the document to which this node belongs  
documentElement Node  return html node  
document.body Node  return body node  
//element Methods:  
getAttribute(attributeName) String  Returns the value of the specified property  
setAttribute(attributeName,value) String  Assign a value to an attribute  
removeAttribute(attributeName) String  Removes the specified property and its value  
getElementsByTagName(name) NodeList  Returns the set of all matched elements within the node  
//node Methods:  
appendChild(child) Node  Adds to the specified node 1 I have a new child  
removeChild(child) Node  Removes the children of a specified node  
replaceChild(newChild,oldChild) Node  Replaces the children of the specified node  
insertBefore(newChild,refChild) Node  In the same 1 A new node is inserted before the node of the hierarchy  
hasChildNodes() Boolean  Returns if the node has children true 
//node Properties:  
nodeName String  Store the node name as a string  
nodeType String  The type of node stored in an integer data format  
nodeValue String  Store node values in an available format  
parentNode Node  A reference to the parent of a node  
childNodes NodeList  A collection of references to children  
firstChild Node  Points to the row in the combination of child nodes 1 A reference to a child  
lastChild Node  Points to the end of the combination of child nodes 1 A reference to a child  
previousSibling Node  Point to the former 1 Three sibling nodes; If the node is a sibling node, the value is null 
nextSibling Node  After pointing to 1 Three sibling nodes; If the node is a sibling node, the value is null

3. 1 map object searched online:


function HashMap() 
{ 
/** Map  The size of the  **/ 
var size = 0; 
/**  object  **/ 
var entry = new Object(); 
/**  save  **/ 
this.put = function (key , value) 
{ 
if(!this.containsKey(key)) 
{ 
size ++ ; 
} 
entry[key] = value; 
} 
/**  take  **/ 
this.get = function (key) 
{ 
return this.containsKey(key) ? entry[key] : null; 
} 
/**  delete  **/ 
this.remove = function ( key ) 
{ 
if( this.containsKey(key) && ( delete entry[key] ) ) 
{ 
size --; 
} 
} 
/**  Does it include  Key **/ 
this.containsKey = function ( key ) 
{ 
return (key in entry); 
} 
/**  Does it include  Value **/ 
this.containsValue = function ( value ) 
{ 
for(var prop in entry) 
{ 
if(entry[prop] == value) 
{ 
return true; 
} 
} 
return false; 
} 
/**  all  Value **/ 
this.values = function () 
{ 
var values = new Array(); 
for(var prop in entry) 
{ 
values.push(entry[prop]); 
} 
return values; 
} 
/**  all  Key **/ 
this.keys = function () 
{ 
var keys = new Array(); 
for(var prop in entry) 
{ 
keys.push(prop); 
} 
return keys; 

} 
/** Map Size **/ 
this.size = function () 
{ 
return size; 
} 
/*  empty  */ 
this.clear = function () 
{ 
size = 0; 
entry = new Object(); 
} 
} 
var map = new HashMap(); 
/* 
map.put("A","1"); 
map.put("B","2"); 
map.put("A","5"); 
map.put("C","3"); 
map.put("A","4"); 
*/ 
/* 
alert(map.containsKey("XX")); 
alert(map.size()); 
alert(map.get("A")); 
alert(map.get("XX")); 
map.remove("A"); 
alert(map.size()); 
alert(map.get("A")); 
*/ 
/**  You can also treat objects as  Key **/ 
/* 
var arrayKey = new Array("1","2","3","4"); 
var arrayValue = new Array("A","B","C","D"); 
map.put(arrayKey,arrayValue); 
var value = map.get(arrayKey); 
for(var i = 0 ; i < value.length ; i++) 
{ 
//alert(value[i]); 
} 
*/ 
/**  Make an object Key when   , automatically called the object  toString()  methods   In fact, in the end String The object of Key**/ 
/**  If it's a custom object   I'll have to rewrite it  toString()  methods   Otherwise,  .  Here's what happens  **/ 
function MyObject(name) 
{ 
this.name = name; 
} 
/** 
function MyObject(name) 
{ 
this.name = name; 
this.toString = function () 
{ 
return this.name; 
} 
} 
**/ 
var object1 = new MyObject(" Xiao zhang, "); 
var object2 = new MyObject(" nickname "); 
map.put(object1," Xiao zhang, "); 
map.put(object2," nickname "); 
alert(map.get(object1)); 
alert(map.get(object2)); 
map.remove("xxxxx"); 
alert(map.size()); 
/**  The results   nickname   nickname  size = 1 **/ 
/**  If I write it as carbon toString() Object of a method  ,  The effect is not at all 1 The sample  **/ 

4. Common number functions:


// ・ digital type (Number) 
//1. The statement  
var i = 1; 
var i = new Number(1); 
//2. Conversion between strings and Numbers  
var i = 1; 
var str = i.toString(); // The results of : "1" 
var str = new String(i); // The results of : "1" 
i = parseInt(str); // The results of : 1 
i = parseFloat(str); // The results of : 1.0 
// Pay attention to : parseInt,parseFloat the 1 A similar to the "32G" The string , Cast into 32 
//3. Determine if a number is valid  
var i = 123; var str = "string"; 
if( typeof i == "number" ){ } //true 
// In some way ( Such as :parseInt,parseFloat) Returns the 1 A special value NaN(Not a Number) 
// Please note that the first 2 In the point [ Pay attention to ], This method is not entirely suitable for judgment 1 Whether a string is numeric !! 
i = parseInt(str); 
if( isNaN(i) ){ } 
//4. Digital type comparison  
// The knowledge and [ String comparison ] The same  
///5. Decimal turn to integer  
var f = 1.5; 
var i = Math.round(f); // The results of :2 (4 Give up 5 Into the ) 
var i = Math.ceil(f); // The results of :2 ( Return is greater than the f Minimum integer of ) 
var i = Math.floor(f); // The results of :1 ( Back to less than f Maximum integer of ) 
//6. Formatted display number  
var i = 3.14159; 
// A floating-point number formatted as a two-digit decimal  
var str = i.toFixed(2); // The results of : "3.14" 
// Formatted as 5 A floating-point number of bits ( From left to right 5 A digital , Not enough padding ) 
var str = i.toPrecision(5); // The results of : "3.1415" 
//7.X Conversion of base Numbers  
// Is not very good  -.- 
var i = parseInt("0x1f",16); 
var i = parseInt(i,10); 
var i = parseInt("11010011",2); 
//8. The random number  
// return 0-1 Any decimal in between  
var rnd = Math.random(); 
// return 0-n Any integer between ( Do not include n) 
var rnd = Math.floor(Math.random() * n) 

5. js stack:


function stack(){ 
if(this.top==undefined){ 
// Initializes the stack's top pointer and data storage fields  
this.top=0; 
this.unit=new Array(); 
} 
this.push=function(pushvalue){ 
// Define the method to be pushed into the stack  
this.unit[this.top]=pushvalue; 
this.top+=1; 
} 
this.readAllElements=function(){ 
// Defines a method to read all data  
if(this.top==0){ 
alert(" Current stack empty, unable to read data "); 
return(""); 
} 
var count=0; 
var outStr=""; 
for(count=0;count<this.top;count++){ 
outStr+=this.unit[count]+","; 
} 
return(outStr); 
} 
this.pop=function(){ 
// Define the method for the pop-up stack  
if(this.top==0){ 
alert(" Current stack empty, unable to eject data "); 
return(""); 
} 
var popTo=this.unit[this.top-1]; 
this.top--; 
return(popTo); 
/*  Pop data from stack, top pointer subtracted 1 , but here did not do the release of resources, also  
 That means the data is still there this.unit Is just not accessible. At present  
 I didn't think of a good solution. */ 
} 
} 

6. Most commonly used JavaScript date function:


// ・ date type (Date) 
//1. The statement  
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 a part of time  
var myDate = new Date(); 
myDate.getYear(); // Get the current year (2 position ) 
myDate.getFullYear(); // Get the full year (4 position ,1970-????) 
myDate.getMonth(); // Get the current month (0-11,0 On behalf of 1 month ) 
myDate.getDate(); // Get current date (1-31) 
myDate.getDay(); // Get current week X(0-6,0 Representative Sunday ) 
myDate.getTime(); // Get current time ( from 1970.1.1 The first millisecond )  Timestamp!!  
myDate.getHours(); // Gets the current 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( ); // Gets the date and time  
//3. Calculate time before or in the future  
var myDate = new Date(); 
myDate.setDate(myDate.getDate() + 10); // Current time addition 10 day  
// Similar methods are basically the same , In order to set At the beginning , Specific reference regulation 2 point  
//4. Calculate the offsets of the two dates  
var i = daysBetween(beginDate,endDate); // Returns the number of days  
var i = beginDate.getTimezoneOffset(endDate); // Return minutes  
//5. Date of inspection  
//checkDate()  Only allow "mm-dd-yyyy" or "mm/dd/yyyy" Date in both formats  
if( checkDate("2006-01-01") ){ } 
// Regular expression ( Self - written check  yyyy-mm-dd, yy-mm-dd, yyyy/mm/dd, yy/mm/dd 4 Kind of ) 
var r = /^(\d{2}|\d{4})[\/-]\d{1,2}[\/-]\d{1,2}$/; 
if( r.test( myString ) ){ } 

7. API:


// ・ string (String) 
//1. The statement  
var myString = new String("Every good boy does fine."); 
var myString = "Every good boy does fine."; 
//2. String concatenation  
var myString = "Every " + "good boy " + "does fine."; 
var myString = "Every "; myString += "good boy does fine."; 
//3. Truncated string  
// Capture the first  6  The character at the beginning of a bit  
var myString = "Every good boy does fine."; 
var section = myString.substring(6); // The results of : "good boy does fine." 
// Capture the first  0  Bit start to bit end  10  Bitwise characters  
var myString = "Every good boy does fine."; 
var section = myString.substring(0,10); // The results of : "Every good" 
// Intercept from the first  11  Bit to the last  6  Bitwise characters  
var myString = "Every good boy does fine."; 
var section = myString.slice(11,-6); // The results of : "boy does" 
// From the first  6  Bit start intercept length is  4  The character of  
var myString = "Every good boy does fine."; 
var section = myString.substr(6,4); // The results of : "good" 
//4. Case conversion  
var myString = "Hello"; 
var lcString = myString.toLowerCase(); // The results of : "hello" 
var ucString = myString.toUpperCase(); // The results of : "HELLO" 
//5. String comparison  
var aString = "Hello!"; 
var bString = new String("Hello!"); 
if( aString == "Hello!" ){ } // The results of : true 
if( aString == bString ){ } // The results of : true 
if( aString === bString ){ } // The results of : false ( Two different objects , Even though they have the same value ) 
//6. Retrieve string  
var myString = "hello everybody."; 
//  It returns if it does not retrieve it -1, Returns the starting position in the string if retrieved  
if( myString.indexOf("every") > -1 ){ } // The results of : true 
////7. Find replacement string  
var myString = "I is your father."; 
var result = myString.replace("is","am"); // The results of : "I am your father." 
//8. Special characters : 
//\b :  Backward operator  \t :  Horizontal TAB  
//\n :  A newline  \v :  Vertical tabs  
//\f :  Page break  \r :  A carriage return  
//\" :  Double quotation marks  \' :  Single quotes  
//\\ :  The diagonal  
//9. Converts a character to Unicode coding  
var myString = "hello"; 
var code = myString.charCodeAt(3); // return "l" the Unicode coding ( The integer ) 
var char = String.fromCharCode(66); // return Unicode for 66 The character of  
//10. Converts a string to URL coding  
var myString = "hello all"; 
var code = encodeURI(myString); // The results of : "hello%20all" 
var str = decodeURI(code); // The results of : "hello all" 
// And correspondingly : encodeURIComponent() decodeURIComponent() 

8. Mathematical functions:


 ・ Math object  
1. Math.abs(num) :  return num The absolute value of  
2. Math.acos(num) :  return num The arccosine of theta  
3. Math.asin(num) :  return num The inverse sine of theta  
4. Math.atan(num) :  return num The inverse tangent of theta  
5. Math.atan2(y,x) :  return y Divided by the x The inverse tangent of the quotient  
6. Math.ceil(num) :  Return is greater than the num Minimum integer of  
7. Math.cos(num) :  return num The cosine  
8. Math.exp(x) :  Returns the base of a natural number ,x Power number  
9. Math.floor(num) :  Back to less than num Maximum integer of  
10.Math.log(num) :  return num Natural logarithm of  
11.Math.max(num1,num2) :  return num1 and num2 The larger the 1 a  
12.Math.min(num1,num2) :  return num1 and num2 The smaller of 1 a  
13.Math.pow(x,y) :  return x the y The value of the power  
14.Math.random() :  return 0 to 1 Between the 1 A random number  
15.Math.round(num) :  return num4 Give up 5 After the value  
16.Math.sin(num) :  return num The sine value of  
17.Math.sqrt(num) :  return num The square root of  
18.Math.tan(num) :  return num The tangent value of  
19.Math.E :  Natural Numbers (2.718281828459045) 
20.Math.LN2 : 2 Natural logarithm of (0.6931471805599453) 
21.Math.LN10 : 10 Natural logarithm of (2.302585092994046) 
22.Math.LOG2E : log 2  Is the natural number of base (1.4426950408889634) 
23.Math.LOG10E : log 10  Is the natural number of base (0.4342944819032518) 
24.Math.PI :  PI. (3.141592653589793) 
25.Math.SQRT1_2 : 1/2 The square root of (0.7071067811865476) 
26.Math.SQRT2 : 2 The square root of (1.4142135623730951) 

9. Browser feature functions:


//1. Browser name  
//IE : "Microsoft Internet Explorer" 
//NS : "Netscape" 
var browserName = navigator.appName; 
//2. Browser version  
var 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 whether an object is supported , methods , attribute  
// when 1 An object , methods , Property is returned when it is not defined undefined or null Etc. , These are all special values false 
if( document.images ){ } 
if( document.getElementById ){ } 
//5. Check the browser's current language  
if( navigator.userLanguage ){ var l = navigator.userLanguage.toUpperCase(); } 
//6. Check if the browser supports it Cookies 
if( navigator.cookieEnabled ){ } 

10.JavaScript Object-oriented method Implementation inheritance :call method


//  animal  animal 
function animal(bSex){ 
this.sex = bSex 
this.getSex = function(){ 
return this.sex 
} 
} 
//  Static-like variable  ( If you don't fix it ) 
animal.SEX_G = new Object(); //  The female  
animal.SEX_B = new Object(); //  male  
//  Animal subclass   The bird  
function bird(bSex){ 
animal.call(this, bSex); 
this.fly = function(iSpeed){ 
alert(" Flying at top speed  " + iSpeed); 
} 
} 
//  Animal subclass   fish  
function fish(bSex){ 
animal.call(this, bSex); 
this.swim = function(iSpeed){ 
alert(" Swimming speed up to  " + iSpeed) 
} 
} 
//  fish   The bird   Hybrid...  
function crossBF(bSex){ 
bird.call(this, bSex); 
fish.call(this, bSex); 
} 
var oPet = new crossBF(animal.SEX_G); //  The female   The fish bird  
alert(oPet.getSex() == animal.SEX_G ? " The female " : " male "); 
oPet.fly(124) 
oPet.swim(254) 

11. Write JavaScript in object-oriented programming:


//document Methods:  
getElementById(id) Node  Returns a reference to the specified node  
getElementsByTagName(name) NodeList  Returns a collection of all matched elements in the document  
createElement(name) Node Node 
createTextNode(text) Node  create 1 A plain text node  
ownerDocument Document  Points to the document to which this node belongs  
documentElement Node  return html node  
document.body Node  return body node  
//element Methods:  
getAttribute(attributeName) String  Returns the value of the specified property  
setAttribute(attributeName,value) String  Assign a value to an attribute  
removeAttribute(attributeName) String  Removes the specified property and its value  
getElementsByTagName(name) NodeList  Returns the set of all matched elements within the node  
//node Methods:  
appendChild(child) Node  Adds to the specified node 1 I have a new child  
removeChild(child) Node  Removes the children of a specified node  
replaceChild(newChild,oldChild) Node  Replaces the children of the specified node  
insertBefore(newChild,refChild) Node  In the same 1 A new node is inserted before the node of the hierarchy  
hasChildNodes() Boolean  Returns if the node has children true 
//node Properties:  
nodeName String  Store the node name as a string  
nodeType String  The type of node stored in an integer data format  
nodeValue String  Store node values in an available format  
parentNode Node  A reference to the parent of a node  
childNodes NodeList  A collection of references to children  
firstChild Node  Points to the row in the combination of child nodes 1 A reference to a child  
lastChild Node  Points to the end of the combination of child nodes 1 A reference to a child  
previousSibling Node  Point to the former 1 Three sibling nodes; If the node is a sibling node, the value is null 
nextSibling Node  After pointing to 1 Three sibling nodes; If the node is a sibling node, the value is null

0

12. Common js methods, including 1 method of form verification, common method of drop-down menu, etc. :


//document Methods:  
getElementById(id) Node  Returns a reference to the specified node  
getElementsByTagName(name) NodeList  Returns a collection of all matched elements in the document  
createElement(name) Node Node 
createTextNode(text) Node  create 1 A plain text node  
ownerDocument Document  Points to the document to which this node belongs  
documentElement Node  return html node  
document.body Node  return body node  
//element Methods:  
getAttribute(attributeName) String  Returns the value of the specified property  
setAttribute(attributeName,value) String  Assign a value to an attribute  
removeAttribute(attributeName) String  Removes the specified property and its value  
getElementsByTagName(name) NodeList  Returns the set of all matched elements within the node  
//node Methods:  
appendChild(child) Node  Adds to the specified node 1 I have a new child  
removeChild(child) Node  Removes the children of a specified node  
replaceChild(newChild,oldChild) Node  Replaces the children of the specified node  
insertBefore(newChild,refChild) Node  In the same 1 A new node is inserted before the node of the hierarchy  
hasChildNodes() Boolean  Returns if the node has children true 
//node Properties:  
nodeName String  Store the node name as a string  
nodeType String  The type of node stored in an integer data format  
nodeValue String  Store node values in an available format  
parentNode Node  A reference to the parent of a node  
childNodes NodeList  A collection of references to children  
firstChild Node  Points to the row in the combination of child nodes 1 A reference to a child  
lastChild Node  Points to the end of the combination of child nodes 1 A reference to a child  
previousSibling Node  Point to the former 1 Three sibling nodes; If the node is a sibling node, the value is null 
nextSibling Node  After pointing to 1 Three sibling nodes; If the node is a sibling node, the value is null

1

Put the following code in the html tag and call js above in head:


//document Methods:  
getElementById(id) Node  Returns a reference to the specified node  
getElementsByTagName(name) NodeList  Returns a collection of all matched elements in the document  
createElement(name) Node Node 
createTextNode(text) Node  create 1 A plain text node  
ownerDocument Document  Points to the document to which this node belongs  
documentElement Node  return html node  
document.body Node  return body node  
//element Methods:  
getAttribute(attributeName) String  Returns the value of the specified property  
setAttribute(attributeName,value) String  Assign a value to an attribute  
removeAttribute(attributeName) String  Removes the specified property and its value  
getElementsByTagName(name) NodeList  Returns the set of all matched elements within the node  
//node Methods:  
appendChild(child) Node  Adds to the specified node 1 I have a new child  
removeChild(child) Node  Removes the children of a specified node  
replaceChild(newChild,oldChild) Node  Replaces the children of the specified node  
insertBefore(newChild,refChild) Node  In the same 1 A new node is inserted before the node of the hierarchy  
hasChildNodes() Boolean  Returns if the node has children true 
//node Properties:  
nodeName String  Store the node name as a string  
nodeType String  The type of node stored in an integer data format  
nodeValue String  Store node values in an available format  
parentNode Node  A reference to the parent of a node  
childNodes NodeList  A collection of references to children  
firstChild Node  Points to the row in the combination of child nodes 1 A reference to a child  
lastChild Node  Points to the end of the combination of child nodes 1 A reference to a child  
previousSibling Node  Point to the former 1 Three sibling nodes; If the node is a sibling node, the value is null 
nextSibling Node  After pointing to 1 Three sibling nodes; If the node is a sibling node, the value is null

2

This is the end of this article, I hope you enjoy it.


Related articles: