javaScript
1. Background introduction
In order to improve the network speed, it was solved by Brandon Archie of Netscape, who designed js in 10 working days
1. js standard
ECMAScript is a standard, while JavaScript is the language
2. Basic concepts of js
1. What is js
An object-oriented, cross platform, scripting language that relies on html can be implemented.
2. Application scenario:
- Form verification: standardize user input data and interact with background data 2 Web effects: add behavior to the page content and make the page move 3 Game development: aircraft war, playing bricks
js composition diagram - Internet of things: https://zhuanlan.zhihu.com/p/45509947
- h5, the next version of html, is very powerful. At present, we know that h5 is just some tags, which can not perfectly show its strength. After adding js, we can activate the deep-seated functions of these tags.
3. js composition
ECMAScript: Core
BOM: document object model, which provides methods and interfaces for accessing and operating web pages
DOM: browser object model, which provides methods and interfaces for interacting with browsers
3. Basic use of js
1. js write location
1. Tags: script
<body> <script> //Writing position of js code (recommended) </script><-This is a label indicating the end. You can't Scribble, except for the translation character-> <noscript> <p>This page requires browser support (enabled) JavaScript. </p> </noscript> </body>
- The traditional standard is written in the head
- In fact, style and script can be written anywhere
- Modern web is put in the body
- But. Require appeared After JS, most of them are written in the head to realize asynchronous loading and dependency processing
- 6 attributes: ⭐
- async: (optional) indicates that the script will be downloaded immediately without affecting other operations (asynchronous operation) (fill in Boolean)
- Charset (optional) represents the character set of the code specified by the src attribute. Most browsers ignore
- defer: (optional) indicates that the execution is delayed until all documents are parsed and displayed (attribute = = attribute value)
- The address of the js file introduced by the SRC (optional) table
- type: (optional) you can see that it is the language attribute, that is, the script language attribute.
Asynchronous scripts must be executed before the load event of the page, but they may be executed before and after the event is triggered
Realize XHTML recognition
<script> //<![CDATA[ //]]> </script>
2. Import js file
The software uses external files, which is convenient for maintenance, fast cache loading and future trend
<script src="main.js"></script>
3. Notes
//js /* js Multiline comment for */
2. Strict mode
Add "user strict" at the top of js code
Or add at the top of the function
function (){ "user strict"; //Function body }
In strict mode, some uncertainties in ECMAScript3 will be handled and errors will be thrown for some unsafe operations
Anonymous production variables are not allowed. Functions do not point to this. Variables or objects are not allowed to be deleted. Functions are not allowed to be deleted. Formal parameters cannot be renamed
3. js output
-
Document object maturation
document.write("hollo world"); //Output label element class content document.write("<b>Text bold</b>"); document.write("<i>"); document.write("Text tilt"); document.write("</i>");
-
Display in pop-up window
alert("hollo world");
-
Pop up the judgment box
confirm("are you sure");
-
Pop up input box display
prompt("hollo world");
-
Debug window output
console.log("hollo world");
4. Definition of variables
ECMAScript variables are loosely typed
1. var defined variable
var x;//The var keyword is followed by an indicator or variable name. /*Rules of indicator: composed of letters, numbers and underscores, Can't start with a number --- hump nomenclature Cannot conflict with keywords and reserved words */ var a=12;//assignment console.log(a); var a,b;//Define multiple variable declarations at once var c=1,b=2; e= 13;//Implicit declaration console.log(e);
2. let definition
let a=12;//Can only be used within the scope domain
3. Constant definition
const a=1;
5. Type of variable
-
Number type: var num=1;
-
String type: var str="hollo world";
-
Boolean type: var t="true",f="false";
-
Undefined type: var under="undefined";
-
Empty object type: null;
-
Object type:
-
Special form: function, this special type
var arr=[1,2,3]; var age=12; var obj={ name:"obj", sex:"male", age }
It should be noted that both arrays and objects are object types
The first five are simple types or basic types, and the latter are complex types, also known as reference types.
Myth: null==undefined returns true, but the two are completely different.
-
View data type: console Log (typeof indicator) typeof is an operator, not a function
1. Boolean type
Operator: Boolean
data type | Convert to true value | Convert to false value |
---|---|---|
Boolean | true | false |
Sreing | Any string | ”"(empty string) |
Number | Any non-zero value | 0 and NaN |
Object | Any object | null |
Undefined | n/a | undefined |
2. Number type
1. Base system
var a = 0b10;//Binary var a = 010;//octal number system var b = 0xA;//Hexadecimal var c = 0xb;//Lowercase or uppercase letters are acceptable, and hexadecimal is also acceptable console.log(a); //8 console.log(b); //10 console.log(c); //b
2. Scientific counting method
var num = 5e+5; //5 times 10 to the 5th power (larger) var num = 3e-3;//3 times 10 to the - 3rd power (decimal)
3. Floating point precision loss
This is a common problem of floating-point calculation based on IEEE754 values
var a=0.1+0.2;console.log(a);//The result is 0.300000000000000 4 var b=(0.1*10+0.2*10)/10;console.log(b);//Resolution of precision loss
4. Scope
[5e-324, 1.797e+0] exceeding is - Infinity (negative infinity) and infinity (positive infinity)
Infinity cannot be calculated
5,NaN
Example:
var a = 1; var b = 'two'; var c = a - b; console.log(c); // NaN is not a number console.log(typeof c); // NaN: not a number is not a number
In js, NaN is used to represent a non numeric special value. When it is found that the operation cannot be performed, js will not report an error, but will return a NaN
Precautions for NaN:
- The type of NaN is number, which represents a non number
- NaN is not equal to any value, including NaN itself
- You can judge whether it is a number through isNaN(). When false is returned, it means it is a number
6. Application of NaN
var a = 123; var b = "abc"; console.log(isNaN(a)); // false console.log(isNaN(b)); // true console.log(isNaN(c)); // true
The isNaN() function is used to detect whether the data is of non numeric type
7. Conversion
Operator: Number
3. Character type
1. Escape character
console.log("\""); /* Single quotation marks can't wrap single quotation marks, but can only wrap double quotation marks, that is, you can't wrap yourself. It's really not possible to use backslash \ escape character (\) */
Symbol | significance |
---|---|
\n | Line feed |
\t | Tab |
\b | Space |
\ | Slash |
'' | Single quotation mark |
' | Double quotation mark |
2. Character splicing
var lang="Java";lang+="Script";console.log(lang); var lang="num";lang+=1;console.log(lang);
3,toString()
All types except null and undefined can be converted to strings using toString
But the object is converted to string and output as [object Object]
var str=true.toString();
Special application
Convert decimal to other decimal, and the output result is a string
let num=10; console.log(num.toString());//"10" console.log(num.toString(2));//"1010" console.log(num.toString(8));//"12" console.log(num.toString(10));//"10" console.log(num.toString(16));//"a"
4,String()
The concept is the same as toString(), but the usage is different
var str=String(true);
5. Template string
let a=97; let str=`a=${a}`; console.log(str);//a=97; //Not only that, you can also output spaces console.log(`a b`);//a b
4. object type ⭐⭐
1. Concept ⭐⭐⭐
The object in ECMAScript is actually a collection of data and functions. All new variable types are objects.
2. Object creation
let obj=new Object();//Omitting parentheses is not recommended let arr=new Array();//Create an array object
3. Properties and methods ⭐
Each object type of data has the following properties and methods (except DOM & BOM of the host object)
-
Constructor: retains the function used to create the current object, that is, the constructor is Object();
-
hasOwnProperty(propertyName): used to detect whether the given property exists in the current instance. The property name as a parameter must be specified in string form, such as obj hasOwnProperty("name")
-
isPrototypeOf(object): used to detect whether the incoming object is the current prototype
-
propertyIsEnumerable(propertyName): used to detect whether a given property can be enumerated using a for in statement
-
toLocaleString(): returns the string representation of the object;
-
toString(): returns the string representation of the object;
-
valueOf(): returns the string, numeric value or Boolean value display of the object ❓❓❓
5. All 6 are output [object]
6. Rounding retention
1. parseInt rounding keyword
1.1 decimal rounding
var a=89/5; c=parseInt(a);//C = rounding of a
1.2. Take the first number of the string
Normal condition
var a="123abc" var c=parseInt(a);//C = number before a
exceptional case
var a="a12a12" var c=parseInt(a);//c=NaN
2. Float float
var a="3.14"; var b=parseFloat(a);
The effect is not obvious.
3. Take the decimal places ToFixed:
var a=3.141592453589; var c=a; console.log(c.toFixed(2)) //Keep two decimal places //The output result is a string //The output is a string
7. Operation operator
1. Assignment "="
var a=1; a=10;console.log(a);
2. Four operations:
+ - * / ++ -- += -= *= /=
Special use
var str="10.1"; str=+str;console.log(str);//At this time, str is converted to Number type, and the minus sign can also be used in this way;
All but + can convert strings containing valid digits to numeric types
3. Character operation (string splicing)
var a="hollo",b="world",c=a+b;console.log(c);//holloworld var a="a Value of=",b=1,c=a+b;console.log(c);//Value of a = 1
4. Comparison operation (relation operation)
> < >= <= == ===
Ternary operation: a > b? a:b
-
==(judge whether the values are relative or not, regardless of whether they are of the same type)
-
===(first judge whether it is of the same type, and then judge whether the values are equal)
var a=12,b="12"; console.log(a==b,a===b)//true false
5. Logical operation
& | ! ~ && ||
Bitwise non
var num1=25; var num2=~num1; console.log(num2);//-26
Bitwise AND
var result=25&3;console.log(result);//1
Bitwise OR
var res=25|3;console.log(res);//27
Positional difference
var res=25^3;console.log(res);//26
Shift left
var oldValue=2;//Binary 10 var newValue=oldValue << 5;//1000000 binary, 64 decimal;
Signed right movement
var oldValue=64;//Binary 1000000 var newValue=oldValue >> 5;//Binary 10, decimal 2;
Unsigned right movement
var oldValue=64;//Binary 1000000 var newValue=oldValue >>> 5;//Binary 10, decimal 2; var oldValue=-64; var newValue=oldValue >> 5;
Short circuit operation ⭐⭐
var res=true&&false;console.log(res); var res=true||false;console.log(res);
Can be used to solve compatibility problems
8. Statement
1. If else statement: omitted
2. Do while statement
var i = 0; do{ i += 2; }while(i<10); console.log(i);
3. while statement
var i=0; while(i<10){ i+=2; }
4. for statement
for(var i=0;i<5;i++){console.log(i);} for(let i=0;i<5;i++){ for(let j=0;j<4;j++){ console.log(i+j); } } for(;;){console.log("hollo world")}//Infinite loop //Note that the parameters in for can be proposed, but judgment conditions should be added to stop the cycle
5. For in statement
An iterative statement used to enumerate data traversing object types
for(let i in arr){console.log(i,arr[i])}; for(let key in obj){console.log(key,obj[key])};
Note: null and undefined cannot be used
6. label statement
Using the label statement, you can add labels to your code for future use
start:for(var i=0;i<count;i++){console.log(i);};
7. break and continue statements
- break is to end the current statement, and the following statements will no longer be executed;
- continue is to skip an execution step and then execute the code of the next step;
- outermost in a double for loop, the inner one skips the outer one; (not used)
8. with statement ⭐
var qs=location.search,substring(1); var hostName=localtion.hostname; var url=localion.href; //Use the with statement to bring out the locality for public use with(location){ var qs=search,substring(1); var hostName=hostname; var url=href; }
9. switch statement
let num=2; switch(num){//This parameter can be a string or true. case num=1: console.log(num); break; case num=2: console.log(num); break; case num=3: console.log(num); break; }
Note: switch has the nature of penetration. If there is no break, it will be executed from top to bottom as long as it meets the case conditions
This property can be used reasonably
10. Function
function fn(){ console.log("hollo world"); } fn(); //Deconstruct function call with assignment + default value function add(num,{a,b},[c,d],e=15){ console.log(num+a+b+c+d+e); //The return result is return return num+a+b+c+d+e; //Return. All the codes after return will no longer be executed. End of function } console.log(add(1,{a:2,b:3},[4,5])+15);//30 45 //Anonymous functions are called (function(){})(); function(){}(); var fn=function(){}; div.onclick=function(){}; ~function(){}();//I can't use it. I really don't understand /*****Arrow function*****/ let fn=()=>{};fn(); let fn=res=>console.log(res);fn(20);//Parentheses are not required for a single argument or a single function body let fn=(a,b)=>a+b;console.log(fn(1,2));//Direct return to a+b /*****Function default****/ let fn=(a,b=10)=>a+b;console.log(fn(1));
Note: you can access the parameter array of a function through the arguments object,
A function can be assigned and called multiple times without overloading
11. For of statement
The use and effect are the same as for in, but it can't traverse objects and can use arrays
12. Try catch statement
Execute the contents in try first. If an error occurs in the contents of try, then execute the contents in catch.
try { adddlert("Welcome!"); } catch(err) { document.getElementById("demo").innerHTML = err.message; }
4. Volume, domain, memory
1. Quantity reference
-
You can only add attributes to reference types, not to base types
-
When copying or saving a variable, the operation is the reference of the object, but when adding a property or method, the operation is the actual object.
-
Functions cannot be accessed by reference, but only by value (object special case)
-
The parameters of a function are local variables of the function
-
Function parameter passing object
let obj=new Object({a:1,b:2}); //Situation 1 function fn({a,b}){ a+=2,b+=3; return {a,b}; //The effect of the study is the same whether return is added or not } fn(obj); console.log(obj); //At this time, obj does not change. This is deconstruction assignment, and the function is accessed by value //Situation II function fn1(obj){ obj.a=5; } fn1(obj); console.log(obj); //At this time, the obj changes. Here, it is accessed by reference //Situation III function fn2(obj){ obj.a=3; obj=new Object(); //When the parameter in the function re creates an object, it becomes a local variable and no longer shares an object reference address with the external object. And this object is automatically destroyed after the function is executed ⭐⭐⭐⭐⭐ obj.name='jack'; } fn(obj); console.log(obj); //At this time, the a attribute of obj changes, but the name attribute is not added
2. Data type detection:
-
typeof: omitted
-
instanceof: check whether the data is of the specified type
console.log("231" instanceof Array);//false
Note: all reference type data are instances of Object
-
console. Dir (element): returns the full details of the element
3. Environment and scope
Execution context:
-
The window object is considered as the global execution environment (the top object always points to the window object, and the two are exactly the same)
-
A function body is also an execution environment
-
After the code in an environment is executed, the environment and variables are destroyed. The global execution environment of window objects is destroyed when the browser is closed
-
Scope chain and active object
let color="blue";//Create global variable function fn(){ if(color==="blue"){color="red";} else{color="blue";} } fn(); console.log(color);
The function here is called without parameters, but the color variable is used in it. However, if there is no color variable in the internal execution environment of the function, it will look up to the next level until it is in the global execution environment. If there is no color variable in the global environment, an error will be reported.
function fn(){ var color="red"; if(color==="blue"){color="red";} else{color="blue";} } fn(); console.log(color);
At this time, a color variable is created in the function execution environment, but it can be used in the global environment (except return ing the variable). All cannot output the color variable in the global environment, and the color variable is destroyed after the function is executed.
-
Delay scope chain 🌙
The principle is that some statements temporarily add a variable object at the front end of the scope chain, and the variable object will be removed after code execution.
- Catch block of try catch style
- with statement
???
-
No block level scope
That is, the variables from var in if and for styles can be used globally, but not functions
4. Garbage collection
1. Introduction
javaScript has an automatic garbage collection mechanism.
Principle: find out those variables that are no longer used, and then release the memory occupied by them. There is a time interval and periodicity.
- Method 1: Mark clearing
- Mode 2: application counting
Performance issues: the short garbage collection cycle of IE browser leads to frequent garbage collection, which is the infamous performance prototype of IE6. IE7 rewrites the garbage collection mechanism.
2. Use
Call window The collectgarbage() method performs garbage collection immediately
3. Manage
Dereference: once the data is no longer used, it is best to release its reference by setting its value to null.
Function: it is convenient for the garbage collection mechanism to clear it next time
5. Reference type (method set)
It is often called class or object definition, but it is not the same concept as class
Due to the lengthy introduction in the official, the dry goods are delivered directly
Type detection is in Chapter 4
1. Object type
1. Examples
var person = new Object(); var person = { name:'jack', age:20, eat:function(){ console.log('can't afford to eat sth.'); }, };
2. Properties and methods
var age=20; person.age;//Relatively special person.name='jack'; person.eat=function(){ console.log('have a good appetite'); } //Properties and methods are overwritten writes, that is, modify and reset //The newly added property name or method name cannot be duplicate delete person.age//Delete a property //There is no length attribute to read the length ⭐⭐⭐
3. Property read
console.log(person); person.eat();//Call a property's method var str='name'; var nume=person.name; var userName=person['name']; var theName=person[str]; //These three variables store the same data
4. Object conversion array
1. Generate an array of property names:
Object.keys(person)
2. Generate an array of property values:
Object.valuse(person)
5. Traversal
Traversal can use the for in traversal method
for in traversal method
for(let i in obj){ console.log(obj[i]) } //The string of each attribute of obj stored in each i at this time
6. JSON conversion
It can be used as long as it comes from an Object instance
- let str=JSON.stringify(obj) object to string
- let obj=JSON. STR objects to strings
7. Deconstruction assignment ⭐
var {a,b,c=3}={a:2,b:3}; console.log(a,b,c); //perhaps const a=1; const obj={a,b:2,c:5}; cobsole.log(obj);
8. Expand merge
let obj={a:1,b:2}; let oaj={...obj,c:4,d:5};//Expand obj console.log(oaj);
2. Array type
1. Examples
let arr=new Array(); let arr=[]; //Note that if there is only one value in Array(), the length of the array is defined as this value let arr=[1,2,3]; let arr=new Array(1,'hollo world',{name:'jack'}); let arr=[1,'hollo world',{name:'jack'}];
2. Array reading
console.log(arr); console.log(arr[0]);//The index of the first element of the array is 0 console.log
3. Length of array
let len=arr.length;//Use the length attribute to get the length //If the array length is set to be less than the original length, the element data with the difference will be deleted. If it is greater than the original length, an undefined supplement will be added
4. Array method
-
array.splice(Who starts,Number of deleted[,Replacement 1,Replacement 2,...]); array.splice(1,2)
-
array.push(New element);//Add from last
-
array.pop();//Delete last
-
array.unshift(New element)//Add from scratch
-
array.shift();//Delete one from scratch
-
array.sort();//Elements are sorted by ASCII code from small to large
-
array.sort(function(a,b){return a-b}); //Elements are sorted by value from small to large
-
array.sort(function(a,b){return b-a}); //Elements are sorted by value from large to small
-
array.reverse();//Reverse array
-
array.concat(Another array);//Splice another array behind the array
-
array.join('character');//Add 'character' between elements and return string
-
array.toString();//Convert array to string
-
array.slice(Who starts,Which end); //Read the specified position, including the start position and excluding the end position
-
array.indexOf(element); //Find the position subscript of the element for the first time from the beginning, and the element does not exist. Go back to - 1;
-
array.lastIndexOf(element); //Find the position subscript of the element for the first time from the tail, and the element does not exist. Go back to - 1;
-
array.forEach(function(v,i,array){ //Function body, }); //Parameter 1: element; Parameter 2: subscript; Parameter 3: current array; //Used to traverse an array
-
array.every(function(v,i,array){ //Judgment function body }); //Judge whether each element meets the condition of true, otherwise judge whether all elements meet the condition of false
-
array.some(function(v,i,array){ //Judgment function body }); //Judge whether each element meets the judgment conditions. If one element meets the anti true condition, all elements will be anti false
-
array.map(function(v,i,array){ //Function body }); //Each element of the array is changed and a new array is generated, and the original array remains unchanged
-
array.filter(function(v,i,array){ //Judgment function body }); //Filter the elements that meet the judgment conditions and return a new array, and the original array remains unchanged
-
array.find(function(v,i,array){ //Judgment function body }); //Filter the elements that meet the judgment conditions, find and return the first element, and return false if not found
-
array.findindex(function(v,i,array){ //Judgment function body }); //Filter the elements that meet the judgment conditions, find and return the subscript of the first element, and return - 1 if not found
-
array.include(v);//Judge whether the array contains v and inverse Boolean value
5. Traversal of array
You can use for in traversal, and it is easier to use forEach and other methods
6. Deconstruction assignment
const [a,b,c,d=8,[e,f]]=[1,2,3,5,[6,8]]; console.log(a,b,c,d,e,f);
7. Expand merge
arr=[1,2,3]; console.log(...arr);//1,2,3 //About to arr expand fn(1,2,3); let fn=(...arr)=>console.log(arr);//Combine numbers into an array
3. Data time type
UTC international coordinated time
1. Get time
A time object is created
let data= new Data();//Get current time let data=new Data("2015-2-18");//Gets the specified date let data=new Data("2015-2-18 06:05:52");//Gets the specified time and date let data=new Data(1543499394644);//Gets the specified timestamp time let data=+new Data();//Get the current timestamp
You can also get the specified time through the created data object. This method is not commonly used
data.parse("2015-2-18 06:05:52");//Gets the specified time and date data.UTC(1543499394644)//Gets the specified timestamp time
2. Processing time
Obtain the time period by obtaining the time difference between the current time before and after different times
3. Time formatting
- toDateString() - displays the day of the week, month, day, and year in an implementation specific format
- toTimeString() - displays the hour, minute, second, and time zone in an implementation specific format
- toLocaleDateString() - displays the day of the week, month, day, and year in a region specific format
- toLocaleTimeString() - displays the hours, minutes, and seconds in an implementation specific format
- toLocaleString() - – - displays UTC dates in an implementation specific format
4. Time object method
1. Get time starts with get
//They are all return values, and the timestamp is the number of milliseconds data.getTime();//Time to milliseconds data.setTime();//Millisecond revolution time data.getFullyear();//Take 4 as the year data.getUTCFullYeat();//The year turns to milliseconds, and the UTC date is obtained as long as UTC is added after it data.getMonth()//; Get the month. Note that the return value is 1 less than the current month data.getDate();//get date 🌙 data.getDay();//Get week 🌙 data.getHours();//Get hours data.getMunutes();//Get minutes data.getSecinds();//Get seconds data.getSeconds();//Get milliseconds //Difficult to use data.getMilliseconds();//Number of milliseconds in date data.getTimezoneOffset();//Returns the minute difference between local time and UTC time
2. Set / modify time starts with set
Replace get with set, and the method changes from the return value to the set value
5. Time localization
let allTime=data.toLocalString();//Full localization let dateTime=data.toLocalDateString();//Localization date only let Time=data.toLocalTimeString();//Localization time only
4. RegExp regular type
1. Regular expression writing
let reg=/Regular body/[sign]; let reg=/at/g; let reg=new RegExp(/at/i);
2. Sign
- g: Global mode, which applies to all characters of the checked string and returns the first one when found
- i: Case insensitive
- m: Multiline mode
Can write together
let reg=/at/gi
3. Regular metacharacter
- Matching number: \ d
- Match any non numeric character: \ D
- Match letters or numbers or underscores: \ w
- Matches any character other than letters, numbers, underscores: \ W
- Match any whitespace: \ s
- Match any character that is not a blank character [^ note 1]: \ S
- Match any single character except newline:
- Indicates the text that matches the beginning of the line (starting with whom) [Note 2]:
- Indicates the text that matches the end of the line (end with whom) [^ note 3]:$
4. Regular qualifier
- Repeat zero or more times:*
- Repeat one or more times:+
- Repeat zero or once:?
- Repeat n-1 times: {n}
- Repeat n or more times: {n,}
- Repeat n to m-1 times: {n,m}
5. Regular others
- The string is enclosed in square brackets to match any of the characters, which is equivalent to or: []
- Match content except brackets: [^]
- Escape character:\
- Or, choose one of the two. Note that the left and right sides are divided into two parts, regardless of how long and messy the left and right sides are: | example: let reg = / (male | female) /;
- Select one of the two direct quantities and group [^ note 4]: ()
- Matching Chinese characters: [\ u4e00-\u9fa5]
- Parentheses (): matches the string in parentheses, which can be one or more. It is often used with the "|" (or) symbol. It is a multi-choice structure
6. # regular use ⭐
-
Match - regular expression Test (string); Inverse Boolean
-
Find - string Search (regular); Filter the part that meets the conditions, inverse subscript, no result, - 1;
-
Extract - string Match (regular); Extract the part that meets the conditions and invert the array;
-
Extract - regular Exec (string); Extract the first and inverse results that meet the conditions;
-
Replace - string Replace (regular, new content); Replace regular content with new content
-
Fuzzy Lookup - string Search (regular);
var text='cat bat sat fat'; var pos=text.search(/at/);//Returns the position where at first appears, and returns - 1 if none console.log();//1 result=text.search(/.at/g,'word($1)'); console.log(result);//Find at position, replace from word(.at) //word(cat),word(bat),word(sat),word(fat)
-
Reference substitution
var str = '8/1/2019'; var reg = /(\d)\/(\d)\/(\d+)/; var res = str.replace(reg,"$3/$1/$2"); console.log(res);//2019/8/1
7. Official supplement
var text='this ha a short summer'; var pattern=/(.)hort/g; if(patter.text(text)){ console,log(RegExp.input);//this has been a short summer console,log(RegExp.leftContext);//this has been a console,log(RegExp.rightContext);//summer console,log(RegExp.lastMatch);//short console,log(RegExp.lastParen);//s console,log(RegExp.multiline);//false } /* input Returns the original string leftContext Return to the left of the result rightContext Returns the to the right of the result lastMatch Return results lastParen Returns the number of parentheses that match the captured The last one failed 😅 */
5. Function type
1. No overload
Is the function duplicate name coverage.
2. A pit
sum(); var sum=function (){ console.log(1); } //sum is not function fn() function fn(){ console.log(2); }; //No error will be reported at this time
3. Function as value
In ECMAScript, the function itself is a variable, which means that a function can also be used as a value
4. Function internal properties
1. arguments property,
I haven't seen it, I haven't used it, and an error is reported in strict mode. Recursive function
function fn(n){ if(n<1){ return 1; }else{ return n*fn(n-1); } } //Rewrite function fn(n){ if(n<1){ return 1; }else{ return n*arguments*callee(n-1); } }
The explanation is that such rewriting can release the close coupling between function execution and function name fn
2. this attribute
The pointer in the function points to window by default.
When binding an event, it usually points to this event. However, the function triggered by the event function does not point to this event. You can modify (jump) through call, apply and bind in es6
3. Change the direction of this
Function: they all change the direction of this, but the forms of parameters are different
1. call method
Function: call this function and modify the direction of this in the function
Detailed explanation of parameters:
The first parameter: write whoever this points to in the function
Subsequent parameters: the arguments to be passed in by the called function, separated by commas
2. apply method
Function: call this function and modify the direction of this in the function
**Syntax: * * function name Apply (object, array);
Detailed explanation of parameters:
The first parameter: write whoever this points to in the function
The second parameter: pass in an array to store the arguments required by the called function
3. bind method
Function: without calling the function, clone a new function, modify the direction of this in the new function, and return the new function
**Syntax: * * function name Bind (object [, argument]);
Detailed explanation of parameters:
The first parameter: write whoever this points to in the function
Subsequent parameters: the arguments to be passed in by the called function, separated by commas
3. prototype construction
Function name prototype() access function prototype
4. Function packaging
Outside the code, there is a well-known function that is not called. Set the required parameters to this well-known parameter, and the code is encapsulated.
5. Deconstruction assignment
function fn({a,b}){ console.log(a,b,123); } fn({a:1,b:3});
6. boolean type
6 +, number type
- Method of formatting numerical value: toExponential(), convert to e notation
- toFixed(), toPrecision(), to be checked
7. string type
Direct methods are all return values. String regular methods have been listed in the regular introduction.
str.charAt(subscript);//Find subscript position character str.charCodeAt(subscript);//ASCII code for finding subscript position characters str.concat(Another string);//Append a string. Do not use this property. Use+ //The second parameter of the following three methods can be negative. str.slice(Start position,End position);//Intercept from the start position to the end position, excluding the end position str.substring(Start position,End position);//Intercept from the start position to the end position, excluding the end position str.substr(Start position,Number of interceptions);//Intercept the specified number from the starting position /***********************/ str.indexOf("s");//The first subscript position of s in the character is queried from the beginning, and anti-1 is not found; str.lastIndexOf("s");//Query the first subscript position of s in the character from the tail, and anti-1 is not found; str.trim();//Clear the extra space on both sides of "o o", and the space in the middle cannot be cleared str.toUpperCase();//Character to size str.toLowerCase();//Character to lowercase /*Contains two unusual toLocaleUpperCase();And tolocalelovercase(); It is used in specific areas, such as (Turkish) */ //split returns a numeric value str.split(","[,number]); //Split the string with comma "," and [get the specified number] and splice it into a numerical value in the same order str.split(regular[,number]);//Crack with regularity. str.localeCompare(Column string);//Compare the size of the asicll code of the first character, which is not commonly used String.formCharCode(asicll code[,Multiple values can be filled in]);//Return string to clasil str.startsWith("character");//Judge whether it starts with "character" and return Boolean value str.endsWith("character");//Judge whether it ends with "character" and return Boolean value str.include("character");//Judge whether it contains "character", inverse Boolean value
//Encrypt string function compileStr(code){ var c=String.fromCharCode(code.charCodeAt(0)+code.length); for(var i=1;i<code.length;i++){ c+=String.fromCharCode(code.charCodeAt(i)+code.charCodeAt(i-1)); } return escape(c); } //Decrypt string function uncompileStr(code){ code = unescape(code); var c=String.fromCharCode(code.charCodeAt(0)-code.length); for(var i=1;i<code.length;i++){ c+=String.fromCharCode(code.charCodeAt(i)-c.charCodeAt(i-1)); } return c; }
8. Golbal object
Golbal (global) object is the most special object, an object that doesn't exist at all
1. Encoding and decoding of url
Encode the URL through encodeURL() and encodeURLComponent()
var uri="http://www.wrox.com/illegal calue.htm#start"; console.log(encodeURL(uri)); //The result is:“ http://www.wrox.com/illegal calue. htm#start" console.log(encodeURLComponent(uri)) //The result is: //"http%3A%2F%2Fwww.wrox.com%2Fillegal%20value.htm$23start"
The first one won't encode the special characters of the URL, the second one will, but the second one is confidential
The corresponding decodes are decodeURL() and encodeURLComponent()
2. Online compilation of eval method
Establish a JavaScript running area and directly run js code. Online compilation is completed in this way.
eval("alert('hi')"); //This code is equivalent to alert('hi');
Try not to use this method to receive data, otherwise malicious code input, code injection, will occur
3. It's all prototypes
Is the prototype of all constructors, that is, it is null, and undefined, none, Object, Array and so on are its properties. The relationship between window and it is very vague. I can't understand it. I need to query the information in addition
9. Math object
Add Math to the front
Math.random();//This is a random number assigned to a variable
All return values
1. Value
E | Returns the arithmetic constant e, which is the base of the natural logarithm (approximately equal to 2.718). |
---|---|
LN2 | Returns the natural logarithm of 2 (approximately equal to 0.693). |
LN10 | Returns the natural logarithm of 10 (approximately equal to 2.302). |
LOG2E | Returns the logarithm of e based on 2 (approximately equal to 1.4426950408889634). |
LOG10E | Returns the logarithm of e based on 10 (approximately equal to 0.434). |
PI | Returns the PI (approximately equal to 3.14159). |
SQRT1_2 | Returns the reciprocal of the square root of 2 (approximately equal to 0.707). |
SQRT2 | Returns the square root of 2 (approximately equal to 1.414). |
2. Method
abs(x) | Returns the absolute value of x. |
---|---|
acos(x) | Returns the inverse cosine of x. |
asin(x) | Returns the arcsine value of x. |
atan(x) | Returns the arctangent of x as a number between - PI/2 and PI/2 radians. |
atan2(y,x) | Returns the angle from the x-axis to the point (x,y) (between - PI/2 and PI/2 radians). |
ceil(x) | The logarithm is rounded up. |
cos(x) | Returns the cosine of a number. |
exp(x) | Returns the index of Ex. |
floor(x) | Round down x. |
log(x) | Returns the natural logarithm of a number (base e). |
max(x,y,z,...,n) | The highest value of X, Z. |
min(x,y,z,...,n) | Returns the lowest value of x,y,z,..., n. |
pow(x,y) | Returns the y-power of x. |
random() | Returns a random number between 0 and 1. |
round(x) | rounding. |
sin(x) | Returns the sine of a number. |
sqrt(x) | Returns the square root of a number. |
tan(x) | Returns the tangent of the angle. |
10. Enumeration Technology
Enumeration is done through objects
const jieHunEnum={ "1":"married", "2":"unmarried", }; if(obj.isJieHun){//obj object from outside obj.isJieHun=jieHunEnum[obj.isJieHun]; } //Through obj Deconstruct and assign the 1 / 2 value returned by isjiehun const arr=["1","2"]; const hobbyEnum={ "1":"study", "2":"smoking", "3":"Bubble sister" }; const brr=arr.map(v=>hobbyEnum[v]).join(","); //Through the map method, iterate through the enumeration to process the value of the arr array, return a new array, and then join it. console.log(brr);
6. Object oriented programming
One sign of object-oriented languages is that they all have the concept of class
The following is different from the official content. Here is the summary of operation methods to avoid complex principles. You need to consult materials.
Introduction to medicine: the classic problem of elephants entering the refrigerator
Process oriented: I opened the door of the refrigerator, I loaded the elephant in, and finally I closed the door of the refrigerator. I was working all the time. object-oriented: I ordered the refrigerator door'Door open',Let the refrigerator door open by itself. I ordered the elephant'Put it in',Let the elephant put itself in the refrigerator. I ordered the refrigerator door'The door closes',Let the refrigerator door close by itself. The whole process I only command, not work. I face the door of my refrigerator and the elephant is working Myth: elephants and refrigerators must be pure objects. How to command without objects? And elephant and refrigerator work is its internal method.
1. Object operation method settings
- Configurable: indicates whether the attribute can be deleted through delete to redefine it. The default value is true
- Enumerable: indicates whether the for in loop can be used. The default is true
- Writable: indicates whether the value of the attribute can be modified. Default true
- Value: indicates the default value of an attribute, which is undefined by default
- Get: the function called when reading the property. It is underfunded by default
- Set: the function called when writing the attribute. It is underfunded by default
let person={ Object.defineProperty(person,"name",{//What is this defineProperty? writable:false,//Change writable to false value:'jack', }); person.name='rose';//It will be ignored in the non strict mode, and an error will be reported in the strict mode
2. New method
- defineProperties(): define multiple properties
- configurable
- enumerable
- get and set
var book={}; Object.defineProperties(book,{ name:{ writable:true, name:'jack', }, age:{ value:1, }, year:{ get:function{ return this.name; }, }, });
3. Factory mode
It is to use function to write a constructor, also known as factory function, which can create the same objects in large quantities
Constructor considerations:
- Constructors are inherently used to create objects, so they must be used in conjunction with new, or they will not have the ability to create objects
- The return keyword cannot be inside the constructor, because the constructor will automatically return the object. If you return a basic data type, as with no effect, if you return a complex data type, the constructor is meaningless.
- If the parameter is not required for new, the parentheses can be omitted
- People usually capitalize constructors
The constructor at this point has a disadvantage:
Method takes up memory and causes waste
This is the biggest problem with native objects
function Fn(name,age){ this.name=name; this.age=age; this.eat=function(){ console.log("have a good appetite");//Occupy memory } } let fn=new Fn("jack",20);
be careful: ⭐⭐⭐⭐⭐
Serious factory function
function Person(){ Person.prototype.name='jack'; Person.prototype.age=20; }
4. Prototype mode
Add the prototype prototype of the constructor to the public function, so that the instantiated object can use the public function without wasting memory.
/Set the edible function on the prototype fn.protorype.eat=function(){console.log('have a good appetite');};
1. Relation diagram
2. in operator ⭐
Check whether a property is in the object and return Boolean value
let obj={'name':'jack'}; console.log('name' in obj);//The result returns true
The property set on the prototype also returns true
function Fn(){ this.name='jack'; } Fn.prototype.age=20; let fn=new Fn(); console.log('age' in fn);
Extended application: obj getOwnPropertyNames(),obj. The upgraded version of keys () can be used whether enumeration is possible or not.
3. Simpler prototype statement
function Person(){ } Person.prototype={ name:'jack', age:20, }
4. Dynamics of prototype
Is the price method function in operation
Person.prototype.fn=function(){console.log('I'm dynamic');}; Person.prototype={ fn:function(){console.log('Poor');}, }
5. Parasitic mode
Create an object in the constructor, then set the object and return it
function Person(name,age){ var obj=new Object(); obj.name=name; obj.age=age; return obj; } var jack=new Person('jack',20);
Not recommended
6. Safe constructor mode
There is almost no difference between structure and parasitism, so it is not recommended
7. Inherit
1. Prototype chain
[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-5rVfLzhR-1622042557060)(F: \ note file \ media \ 156648554743. PNG)]
That is, the instance object passes__ proto__ A chain of upward access; obj.__proto__ The value of is the obj prototype
2. Prototype inheritance
//This is archetypal inheritance /Inheritance 1: use prototype inheritance to assign the instance object of the parent class to the prototype object of the child class function Animal(){ this.status=()=>{console.log('Rich man');}; this.pa=()=>{console.log('rich');}; } var animal=new Animal(); function Dog(name){//Mom (constructor) this.name=name; } Dog.prototype=animal;//Dad is a rich man. Dad has a showdown. Dad is the prototype //But Dad forgot his mother, that is, the prototype has no constructor var ha=new Dog('Siberian Husky');//This is a grandson's console.log(ha); ha.eat();
3. Borrowing function inheritance
//Borrowing function inheritance function Animal(){ this.pa='Rich'; } Animal.prototype.eat=function(){console.log('How rich');}//Can't inherit money function Dog(name){ Animal.call(this);/⭐Copy function, Dad lied that he was rich, but he had no money this.name=name; } var ha=new Dog('Siberian Husky'); console.log(ha); // ha.eat(); // Error reporting
Using borrowing functions to implement class inheritance can only access the properties of the parent class, not the methods on the prototype of the parent class ⭐
4. Hybrid inheritance
function Animal(){ this.pa='Rich man'; } Animal.prototype.eat=function(){console.log('have a good appetite');} //=> function Dog(name){ Animal.call(this); this.name=name; } //"= this fast is the constructor, mom Dog.prototype=new Animal();//Dad had a showdown Dog.prototype.constructor=Dog;//Dad doesn't remember his mother. Let him remember his mother, that is, point the constructor of the prototype to the original constructor again var ha=new Dog('Siberian Husky'); console.log(ha); ha.eat(); /Hybrid inheritance,Borrow the function to inherit once, and use the prototype to inherit again
5. Parasitic inheritance (abandonment)
8. class of ES6
1. Grammar
It's short for function and prototype
//es6 class Animal{ /Both properties and methods are written in this bracket /That is, No prototype /One entry: method/function-constructor constructor(name,age){ /Use the same method as constructor this.name=name; this.age=age; this.eat();/Direct call eat Function without calling the object after creating the object. } eat(){/This binds the method to the prototype and implements it prototype Function of console.log('Hunger and thirst'); } } var animal=new Animal('zs',20); console.log(animal); animal.eat();
2. Inherit
/Explicit inheritance syntax:
class Subclass extends Parent class{ constructor(){ super(); } }
class Car{ constructor(TheType){ this.Type=TheType; } run(){ console.log('Run fast'); } } class Wow extends Car{ constructor(car){ super();//This is just needed without error reporting. The function generates a this and points to the parent class /super Must be in the first position /You can also completely avoid the parent class, that is, in constructor Manually return an object inside(return obj) this.car=car; } } var car=new Wow('911') console.log(car); car.run(); /Syntax stipulates that a class can only inherit one class, not multiple
3. super example
class Gad{ constructor(angle){ this.angle=angle; this.god='King Xu' } fly(){ console.log("fly"); } } class people extends Gad{ // class people { constructor(name){ super(name)/This adds a pointer to the parent class this,Pass parameters to parent class this.name=name; } } var peo=new people('Xu') console.log(peo);
7. Function expression
1. Recursion
A function calls itself by name
2. Closure
1. Common words:
Function sets form closures!
2. Introduction:
Closure:
A small function is returned inside the large function, which is received by the variables outside the large function, and the small function uses the variables in the large function.
3. Features:
- A function is returned in the function so that large functions can be obtained in the whole world and small functions can be obtained.
- Small functions can change the data in large functions, and this data can be persistent rather than destroyed every time it is called
This form of code is called closure.
In general, every time a function is called, the variables in it will restart, but the closure will not, because the closure space will not be destroyed.
4. Advantages:
-
The scope space is not destroyed, so the variable will not be destroyed, which increases the declaration cycle of the variable
-
Variables inside the function can be accessed outside the function
-
Protect private variables and define variables in functions without polluting the global environment
-
You can make the function execute only once and use it when the event is triggered multiple times
function fn(s){ return function fs(){ if(s){ console.log(s); s=null; }else{ console.log("ok"); } }; } let f=fn("javascript"); f();//javascript f();//ok f();//ok
5. Disadvantages:
- Because it is not destroyed, it will always occupy memory. If it is too much, it will lead to memory overflow
- Because the variables inside the function can be accessed outside the function, the reference relationship between the variables and the internal function always exists, and the memory cannot be destroyed
- It is not particularly convenient to use closures to access
6. To be verified: the principle of closure formation
- Function returns the basic data type. After it is used up, the data will be destroyed.
- Function returns complex data types. After it is used up, the data will not be destroyed.
7. Change to closure
A function shell can also be set outside, a return can be added to the head, or let can create variables.
8. Note that this points to
this in the closure points to something strange. Be careful and interrupt the output more. Check it
3. Mimic block action level
It is to simulate a private scope by using the scope principle of function
function fn(n){ ~function(){ for(var i=0;i<n;i++){ console.log(i) } }(); console.log(i);/report errors, i is undefined,That is, variables in the simulated private scope cannot be accessed }
4. Private variable
Or the variables inside the function do not return or call out, and no one outside can use them.
5. Privileged method
Public methods that have access to variables and functions are called privileged methods
1. Defining privileged methods in constructors
function MyObject(){/Constructor /Using variables and private functions var able=10; function active(){ return false; } //privileged method this.action=function(){ able++; return active(); } }
At this time, private variables can only be accessed through the action attribute of the instantiated object of the constructor
Using usage and privileged members, you can hide data that should not be modified directly, for example; (in this way, you can create a real encapsulation, like jQuery)
function Person(name){ this.getName=function(){ return name; } this.setName=function(value){ name=name } } var person=new Person('jack'); console.log(person.getName());//jack person.setName('rose'); console.log(person.getName());//rose
2. Static private variable
(function(){ var num=10;//private variable function able(){//Private function return false; } Person=function(){};//Constructor /Define public methods on constructor prototypes Person.prototype.public=function(){ num++; return able(); } })
This method is an improved and upgraded version of the previous method, which solves the problem of memory waste of constructors.
3. Module mode (single example)
A constructor can only create one object in heap space. The objects from the constructor instance are equal.
Normal constructor
function Person(){} let n1=new Person{}; let n2=new Person{}; console.log(n1==n2);//false //That is, two objects are created in heap space
Implementation singleton (closure)
let fn=function(name){ function Per(name){//Constructor this.name=name; } let obj;//initialization return function(name){//Return closure function if(obj){//Judgment initialization return obj; }else{ obj=new Per(name); } return obj; }; }(); let a=fn('rose');//Create object a with function let b=fn('jack');//Create object b with function console.log(a==b);//true**
8,BOM
The core of BOM is window object
1. Window relationship and framework (difficult)
The frame is to use the < frames > single label to create a new frame in the frame double label to divide the browser window. For example:
<html lang="en"> <frameset cols="25%,50%,25%"> <frame src="frame_a.htm"> <frame src="frame_b.htm"> <frame src="frame_c.htm"> </frameset> </html>
Each framework has its own window object, which is saved in the farms collection. In the collection, the corresponding window object can be accessed through the index,
Get frames to reference the framework, and use the top object. The top object always points to the frame of the most (outermost) layer
For example, top frames[0]**
**Note: the top object is all equal to the window object
Another window object opposite top is parent. The parent object always points to the immediate upper frame of the current frame. In some cases, parent may be equal to top. In the absence of a framework, parent must be equal to top, that is, both are equal to window
2. Window position
1. screenLeft/screenTop
Is a property used to determine and modify the location of window objects
Use the following code to get the position of the left and top of the window across browsers, so as to solve the compatibility problem
var leftPos=(typepf window.screenLeft==='number')?window.screenLeft:window.screenX; var topPos=(typepf window.screenTop==='number')?window.screenTop:window.screenY;
This property is used in some browsers and is not recommended
2,moveTo()/moveBy
moveTo() receives the x and y coordinate values of the new location, and moveBy() receives the number of pixels moved horizontally and vertically
window.moveTo(0,0);//Move the window to the upper left corner of the screen window.moveBy(-50,100);//Move the window 50px left and 100px down
3. Window size
It is a complex problem, quite complex problem, all kinds of compatibility, compatibility of different versions, compatibility of different manufacturers and compatibility of different modes
IE9+,Safari,Firebox,adopt outerWidth and outerHeight Returns the size of the browser Opear But I have to pass innerWidth and innerHeight Returns the size of the browser Chrome Both can be used ie6 yes document.documentElement.clientHeight and document.documentElement.clientWidth And in standard mode, Hybrid mode yes document.body.clientHeight and document.body.clientWidth
For mobile terminal development, it is recommended to read: Mobile Web development
In addition, resizeTo() and resizeBy() can be used to resize the browser window.
window.resizeTo(100,100);/Adjust to 100 x100 windiw.resizeBy(100,50);/Adjust to 200 x150
**Note: * * it's OK to use this directly (including scroll bar)
- Height of browser window:
let h=window.innerHeight;
- Width of browser window:
let w=window.innerWidth;
4. Browser navigation information
1,window.open() method
/Equivalent to<a href='http://www.baidu.com' target='topFrame'></a> window.open("http://www.baidu.com","topFrame"); /window.open(URL,name,specs,replace)
2,URL:
Optional. Opens the URL of the specified page. If no URL is specified, a new blank window opens
- _ Blank - the URL is loaded into a new window. This is the default
- _ Parent - the URL is loaded into the parent frame
- _ self - URL replaces the current page
- _ URL set loadable - Top
- Name - window name
3,specs
Optional. A comma separated list of items. Support table binary
channelmode=yes|no|1|0 | Whether to display window in theater mode. The default is none. Internet Explorer only |
---|---|
directories=yes|no|1|0 | Whether to add a directory button. The default is yes. Internet Explorer only |
fullscreen=yes|no|1|0 | Whether the browser displays full screen mode. The default is none. The window in full screen mode must also be in theater mode. Internet Explorer only |
height=pixels | The height of the window. minimum. The value is 100 |
left=pixels | The left position of the window |
location=yes|no|1|0 | Whether to display the address field The default value is yes |
menubar=yes|no|1|0 | Whether to display the menu bar The default value is yes |
resizable=yes|no|1|0 | Whether the window can be resized The default value is yes |
scrollbars=yes|no|1|0 | Whether to display the scroll bar The default value is yes |
status=yes|no|1|0 | Do you want to add a status bar The default value is yes |
titlebar=yes|no|1|0 | Whether to display the title block Ignored unless calling an HTML application or a trusted dialog box The default value is yes |
toolbar=yes|no|1|0 | Whether to display the browser toolbar The default value is yes |
top=pixels | The position of the top of the window Internet Explorer only |
width=pixels | The width of the window minimum. The value is 100 |
4,replace
Optional. Specifications specifies whether the URL loaded into the window creates a new entry in the window's browsing history or replaces the current entry in the browsing history. The following values are supported:
- True - the URL replaces the current entry in the browsing history.
- False - the URL creates a new entry in the browsing history.
5,window.close()
Close browser window: window close()
Only applicable to window Open() to open a pop-up window, you can use top Close() closes the window without the user's permission
6. Pop up screen
By detecting window Whether open() is null determines whether the pop-up window is hidden
5. Intermittent call and timeout call
This is the timer. Note that the timer is asynchronous
-
Timer: setinterval (function executed, interval time)
-
Timer: setTimeout (function executed, time delayed)
-
End timer: (it can be mixed and stopped)
- clearInterval(timerId)
- clearTimeout(timerId)
7. Browser dialog information
The browser dialog boxes are alert(), confirm(),prompt(), and print()
When the dialog box pops up, the code will stop executing. Close the dialog box and the code will continue executing
Use the return value of confirm() to judge the user selection of the confirm() dialog box
Use the return value of prompt() to obtain the information entered by the user in the dialog box
8. location object ⭐
attribute | describe |
---|---|
hash | Returns the anchor portion of a URL |
host | Returns the host name and port of a URL |
hostname | Returns the host name of the URL |
href | Return full URL |
pathname | The returned URL pathname. |
port | Returns the port number used by the URL server |
protocol | Return a URL protocol |
search | Return the query part of a URL (? And the following content, that is, the request information of git) ⭐ |
Assignable output, settable
This can be used to obtain the information transmitted by git ⭐
location.href="https://www.baidu.com"; Jump to Baidu console.log(location.href); Current output URL All strings
assign() | Load a new document |
---|---|
reload() | Reloading the current document is refresh |
replace() | Replace the current document with a new one |
9. Navigator object
attribute | explain |
---|---|
appCodeName | Returns the code name of the browser |
appName | Returns the name of the browser |
appVersion | Returns the platform and version information of the browser |
cookieEnabled | Returns a Boolean value indicating whether cookie s are enabled in the browser |
platform | Return to the operating system platform on which the browser is running |
userAgent | Returns the value of the user agent header sent by the client to the server |
1. Detect browser plug-ins
Use navigator Plugins value to achieve this
- Name: plug in name
- Description: description of the plug-in
- filename: the file name of the plug-in
- length: the number of MIME types processed by the plug-in
navigator.plugins: name of a parameter to be detected by the plugin
10. Screen object properties
attribute | explain |
---|---|
availHeight | Returns the height of the screen (excluding the Windows taskbar) |
availWidth | Returns the width of the screen (excluding the Windows taskbar) |
colorDepth | Returns the bit depth of the palette on the target device or buffer |
height | Returns the total height of the screen |
pixelDepth | Returns the color resolution of the screen (bits per pixel) |
width | Returns the total width of the screen |
onLine | Judge whether the network is connected. Yes, no, false |
11. History object
attribute | explain |
---|---|
length | Returns the number of URLs in the history list |
method
method | explain |
---|---|
back() | Load the previous URL in the history list |
forward() | Load the next URL in the history list |
go() | Load a specific page in the history list. Positive is forward and negative is backward |
9. Client detection 🌙
It's just a bunch of compatibility problems. It's a lot of trouble. It's hard to understand and sort out. Don't update first
10. DOM and extensions
1. node object properties
attribute | describe |
---|---|
baseURI | Returns the absolute base URI of the node. |
childNodes | Returns the node list of the child nodes of the node. |
firstChild | Returns the first child node of the node. |
lastChild | Returns the last child node of the node. |
localName | Returns the local part of the node name. |
namespaceURI | Returns the namespace URI of the node. |
nextSibling | Returns the node immediately after the element. |
nodeName | Returns the name of the node, depending on its type. |
nodeType | Returns the type of the node. |
nodeValue | Sets or returns the value of the node, depending on its type. |
ownerDocument | Returns the root element of the node (document object). |
parentNode | Returns the parent node of the node. |
prefix | Sets or returns the namespace prefix of the node. |
previousSibling | Returns the node immediately before the element. |
textContent | Sets or returns the text content of a node and its descendants. |
Several more important
nodeType | Node type, corresponding value, online query |
---|---|
nodeName | Node name |
nodeValue | Node value, mostly used for input tag |
2. Node object method
method | describe |
---|---|
appendChild() | Add the new child node to the end of the child node list of the node. |
cloneNode() | Clone nodes. |
compareDocumentPosition() | Compare the document locations of the two nodes. |
getFeature(feature,version) | Returns a DOM object that executes a specialized API with a specified feature and version. |
getUserData(key) | Returns the object associated with the key on the node. This object must first be set to this node by calling setUserData with the same key. |
hasAttributes() | If the node has an attribute, it returns true; otherwise, it returns false. |
hasChildNodes() | Returns true if the node has child nodes; otherwise, returns false. |
insertBefore() | Insert a new child node before the existing child node. |
isDefaultNamespace(URI) | Returns whether the specified namespace URI is the default. |
isEqualNode() | Check whether the two nodes are equal. |
isSameNode() | Check whether the two nodes are the same node. |
isSupported(feature,version) | Returns whether the specified attribute is supported on this node. |
lookupNamespaceURI() | Returns the namespace URI that matches the specified prefix. |
lookupPrefix() | Returns a prefix that matches the specified namespace URI. |
normalize() | Put all Text nodes under nodes (including attributes) into a "standard" format, in which only structures (such as elements, comments, processing instructions, CDATA sections and entity references) separate Text nodes. For example, there are neither adjacent Text nodes nor empty Text nodes. |
removeChild() | Delete child nodes. |
replaceChild() | Replace child nodes. |
setUserData(key,data,handler) | The key that associates the object to the node. |
3. Node relationship
[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-Coyvys7R-1622042557063)(F: \ note file \ media\timg.jpg)]
4. Get relationship node
- Get all child nodes: childNodes
- Get all child element nodes: children
- Get the first child node: firstChild
- Get the last child node: lastChild
- Get the first child element node: firstElementChild
- Get the last child element node: lastElementChild
- Get the next sibling node: nextSibling
- Get the previous sibling node: previousSibling
- Get the next element sibling node: nextlementsibling
- Get the previous element sibling node: previousElementSibling
- Get parent node: parentNode
- Get parent element node: parentElement
- Number of child elements returned by elementcount; No text and comments
- Judge whether there are child nodes: parent nodes Contains (child node); true is returned, false is not returned
5. Node operation
- ⭐ Create element node: document If the createElement (element label) is below IE7, there will be compatibility problems with the form
- Create text node: document createTextNode("<i>hollo world</i>")
- Create attribute node: document Createattribute (element attribute) [Note 1]
- Create text node: document CreateTextNode (text content)
- Insert node at the end: parent node AppendChild (new node added)
- Head insert node: parent node InsertBefore (new node, existing point)
- Replace node: parent node Replacechild (new node, old element);
- Copy node: the point to be copied CloneNode (true (deep copy) / false (shallow copy)); [^ note 2]
- Delete node: parent element Removechild (node to be deleted);
- Clear all nodes in the parent element: parent element innerHTMML('');
- Node merging: parent element normalize(): merge the child elements together (standardize the format)
- Split node: parent element splitText(): similar to splitting strings
- Class name operation: node className = 'class name'; The assignment can be obtained and modified
- Add class name: node classList.add("class name"); Append a class name
- Delete class name: node classList.remove("class name"); Remove the specified class name
- Switch class name: node classList.toggle("class name"); Add delete switch
- Judge whether it contains such name: node classList.contains("class name"); Returns true if any, and returns false if none
6. Doument type
1. Document object properties
attribute | describe |
---|---|
async | Specifies whether the download of XML files should be processed asynchronously. |
childNodes | Returns the node list of the document's child nodes. |
doctype | Returns the Document Type Declaration (DTD) related to the document. |
documentElement | Returns the root node of the document. |
documentURI | Sets or returns the location of the document. |
domConfig | Returns the configuration used when normalizeDocument() is called. |
firstChild | Returns the first child node of the document. |
implementation | Returns the DOMImplementation object that processes the document. |
inputEncoding | Returns the encoding method used for the document (when parsing). |
lastChild | Returns the last child node of the document. |
nodeName | Returns the name of the node (depending on the type of node). |
nodeType | Returns the node type of the node. |
nodeValue | Sets or returns the value of the node (depending on the type of node). |
strictErrorChecking | Sets or returns whether to force error checking. |
xmlEncoding | Returns the XML encoding of the document. |
xmlStandalone | Sets or returns whether the document is standalone. |
xmlVersion | Sets or returns the XML version of the document. |
2. Document object method
method | describe |
---|---|
adoptNode(sourcenode) | Select a node from another document to this document, and then return to the selected node. |
createAttribute(name) | Create an attribute node with the specified name and return a new Attr object. |
createAttributeNS(uri,name) | Creates an attribute node with the specified name and namespace and returns a new Attr object. |
createCDATASection() | Create a CDATA section node. |
createComment() | Create an annotation node. |
createDocumentFragment() | Create an empty DocumentFragment object and return it. |
createElement() | Create an element node. |
createElementNS() | Creates an element node with the specified namespace. |
createEntityReference(name) | Create an EntityReference object and return it. |
createProcessingInstruction(target,data) | Create a ProcessingInstruction object and return it. |
createTextNode() | Create a text node. |
getElementById(id) | Returns the element with the ID attribute of the specified value. If no such element exists, null is returned. |
getElementsByTagName() | Returns the NodeList of all elements with the specified name. |
getElementsByTagNameNS() | Returns the NodeList of all elements with the specified name and namespace. |
importNode(nodetoimport,deep) | Select a node from another document to this document. This method creates a new copy of the source node. If the deep parameter is set to true, it will import all child nodes of the specified node. If set to false, it will only import the node itself. This method returns the imported node. |
normalizeDocument() | |
renameNode() | Rename an element or attribute node. |
3. Common document
- document.write('page output ');
- document.bgColor=‘#000’;// Add html by default
- document.documentElement;//html and all its contents
- document.head / / content pointing to head
- document.body / / content pointing to body
- document.body.style.color="#000" / / add color to the font in the body
- document.title / / points to the content of title
- document.URL / / get the complete URL of the current page
- document. Refer / / get the URL of the source page
- document. Domain / / refers to the domain name, which can be used to judge the domain name
7. document get node
-
document.getElementById('element Id ')
-
document.getElementByTagName('element node name ')
When accessing, you can directly take the subscript or use item() to take the subscript. You can also use the method of namedItem() to access the attribute value of name
-
document.getElementByClassName('element class')
-
document.getElementByName('name ')
-
document.querySekector("css selector"): find an element and return it
-
document. Queryseketorall ("CSS selector"): find multiple elements and return the set composed of these elements (forEach can be used to traverse the set)
-
Detect whether it is obtained by the above two methods: element Matchsselector ("CSS selector"), refers to anti true, no anti false
8. document special collection (pseudo array)
- document.anchors contains all the special effects with name in the document
- document. Collection of applets
- document. Collection of forms
- document. Collection of images
- document.links said there was a with a href
9. Writing of document
Four methods: write(), writeln(), open(), close()
-
writeln() is also a write string, but adds a newline (\ n) at the end
When a script tag is nested inside a script tag, you can use this attribute to wrap it so that the tag can match the head and tail normally
-
The latter two methods use to open and close the browser's output stream
10. Node attribute style operation
attributes are no longer commonly used
-
Add: element setAttribute("attribute name", "attribute value") [^ remark 7] ⭐
-
Delete: element removeAttribute("attribute name" [, "attribute value"])
-
Change: the attributes of the node are added and modified in an overlay manner
-
Check: elements getAttribute("attribute name")
-
Or directly add, delete, modify and query the attribute in the form of viewing object
div.id='div'; div["id"]='div'; div.style.color='red'; div.style['background-color']='red';
Note: those with "-" and other special symbols can only use this form
-
All of the above are to get and set inline styles. You cannot get css styles that are inline or external
window. Getcomputestyle (element) css attribute name can get all css styles.
-
Get node custom attributes: node dataset. Custom attributes; Available, settable
11. DOM operation technology
It is to dynamically generate a script tag, set the src attribute, or generate a link tag, set the href attribute, and then add the location corresponding to html
12. table method
-
caption: holds the pointer to the element (if any)
-
tBodies: indicates that there is a pointer to the element
-
tFoot: holds the pointer to the element (if any)
-
thead: holds the pointer to the element (if any)
-
Rows: points to all rows
-
Createheader(): creates an element, puts it into a table, and returns a reference
-
createTFoot(): create elements, put them into the table, and return references
-
createCaption(): creates an element, puts it into a table, and returns a reference
-
Deletethread(): deletes an element
-
deleteTFoot(): deletes an element
-
deleteCaption(): deletes an element
-
deleteRow(pos): deletes the row at the specified location
-
Insert rows in the set
Properties and methods added for
-
Rows: point to rows
-
deleteRow(pos): deletes the row at the specified location
-
insertRow(pos): inserts a row at the specified position in the rows collection and returns a reference to the newly inserted row
Properties and methods added for
-
cells: point to td or th
-
deleteCell(pos): deletes a cell at a specified location
-
insertCell(pos): add a cell to the specified location of cells and return a reference to the newly inserted cell
13. Document related
- document.hasFocus(); Determine whether the document gets focus
- document.readyState(); Return to the document loading status: loading is loading and complete loading is completed
- document.charset; Specifies the data type when the document is read
14. Insert tag (innerHTML) ⭐⭐
- Node innerHTML='<p>hollo world</p>'; Can be obtained, can be set, and the label will be displayed after loading. There is a compatibility problem with the script tag
- Node outerHTML; It's useless. The functions and are just to get special exchange, but it's also available on it
- Node insertAdjacentHTML()
- Insert: old node before element insertAdjaceHtml("beforebegin","<p>hollo world</p>")
- Insert after element: old node insertAdjaceHtml("afterend","<p>hollo world</p>")
- First child element insertion: parent node insertAdjacentHtml("afterbegin","<p>hollo world</p>")
- The last element is inserted: parent node insertAdjacentHtml("beforeend","<p>hollo world</p>")
Using innerHTML to manipulate nodes reduces memory usage
15. Insert text
- Node innerText; Only add content, not nodes
- Node outerText;
16. Rolling
All elements can be used (Safari and Chrome implement this method)
- scrollIntoViewIfNeeded([true]) the current container window is missing and visible after scrolling
- scrollByLines(pos) sets the specified line height for element content scrolling
- scrollByPages() sets the specified page height for element content scrolling
11. DOM2 and DOM3
Most of them are wordy and give up directly in teaching. Only the commonly used parts are listed
1. Element size
Read only attribute
- height: element offsetHeight
- width: element offsetWidth
- Positioned parent element: offsetParent (useless)
- left: element offsetLeft
- top: element offsetTop
2. Viewable window size
Without scroll bar
- height: element clientHeight
- width: element clientWidth
- left: element clientLeft
- top: element clientTop
3. Scroll size
- When there is no scroll bar, the total height of element content: element scrollHeight
- When there is no scroll bar, the total width of element content: element scrollWidth
- Distance from left when scrolling: element scrollLeft
- Distance from top when scrolling: element scrollTop
4. Determine element size
Element getBoundingClientRect(), which returns a rectangular object with four attributes: left, right, top and bottom. It's no use
5. Scope
Used to determine the scope of DOM, folding, special complex selection, etc.
12. Events
The interaction between JavaScript and HTML is realized through events.
1. Event flow
1. Event bubbling
The event of the child element will bubble up and trigger the same event of the parent element
2. Event capture
Getting the child element will be captured from the parent element layer by layer, and triggering the parent element will trigger the same event of the child element
3. DOM event flow
Event flow refers to the bubbling phase of events from the capture phase, and each event passes through the event flow
Of course, it can be stopped artificially, which will be described in detail later
2. Event handling
1. Event binding
Take a mouse click event as an example.
1. HTML inline binding
<input type="button" value="Button" onclick="fn"> <!--Click trigger fn Processing function--> <!--You can bind only once. Binding again will overwrite the previous-->
2. on binding
This is to bind an uncalled processing function fn, which is triggered when input is clicked, and this of FN points to input instead of window global. Of course, it can still be changed through call, apply and bind.
let input=document.querySelector("input"); input.onclick=function fn(){ console.log(this.value); } You can bind only once. Binding again will overwrite the previous
3. Add a listening event
The processing function is not called as above. The third parameter is whether to execute in the capture phase. The default is no and false
You can bind different handler functions multiple times. It can be a function name or an entire function, but it can't be called
input.addEventListener("click",Processing function,false);
2. Unbind event
1. Inline binding
Unbind directly with remove attribute
input.removeAttribute("onclick");
2. on unbinding
Set the handler function to null. Overwrite previous settings
input.onclick=null;
3. Delete listening event
The parameters are the same as those in binding
input.removeEventListener("click",Processing function,false);
3. Compatible with IE8 and below
Bind as: attachEvent()
Unbind as: detectevent()
IE8 only supports bubbling. Its usage is the same as monitoring events.
4. Cross browser event handling
This thing has hardly been mentioned. Find out
The addHandler() binding method receives three parameters: the element to be operated, the event name and the event handler function
The corresponding object is removeHandler(). To use EventUtil, please query it online
3. Event object E
Every event triggered on the DOM will generate an event object, which contains all the information related to the event
1. Description of e
Properties / methods | type | Read / write | explain |
---|---|---|---|
bubbles | Boolean | read-only | Indicates whether the event is bubbling |
cancelable | Boolean | read-only | Indicates whether the default behavior of the event can be canceled |
currentTarget | Element | read-only | The element whose event handler handles the event properly |
defaultPrevented | Boolean | read-only | true indicates that preventDefault() has been called |
detail | Integer | read-only | Details related to the event |
eventPhase | Integer | read-only | Call the stage of the event handler, 1 capture, 2 with the target, 3 bubbling |
prevent Default() | Function | read-only | Cancels the default behavior of the event. If cancelable is true, it can be used |
stopImmediatePropagation() | Function | read-only | Cancels further capture or bubbling of events while preventing any events from being called |
stopPropagation() | Functon | read-only | Cancel further capture or bubbling of events. If bubbles is true, you can use |
target | Element | read-only | Target of the event |
trusted | Boolean | read-only | Generated for true table browser and false for developer JavaScript |
type | String | read-only | Type of event triggered |
view | AbstractView | read-only | The abstract diagram associated with the event is equivalent to the window in which the event occurs |
2. Get event object
- window.event
- var er=e || window.event [^ note 8] (short circuit operation is used here)
- box.onclick=function(e){console.log(e)}
3. Common use of e
- Get mouse button information use: e.button: (detailed introduction to mouse events)
- e.type: used to obtain the event type. For example, click is the click event and blur is the lost focus.
- e.keyCode to obtain the key ascll code of pressing the keyboard key
- e.target gets the event target (the precise target element of the event) ⭐
- e.stopPropagation() prevents event bubbling ⭐
- e.preventDefault() prevents the default behavior of the event ⭐ Or append return false at the end of the event handler function, or set javascript: for the link address& javaScript:voidlo)
4. e compatibility
- e. Srclelement obtains the event target (the precise target element of the event) (Firefox browser also obtains it through srclelement)
- e.cancelBubble prevents the event from bubbling
- e.returnValue block event default behavior
5. e get cursor position
- x axis: e.offsetX; y axis: e.offsetY; [^ note 9]
- x axis: e.clientX; y axis: e.clientY; [^ note 10]
- x axis: e.pageX; y-axis: e.pageY; [^ note 11]
6. Event Hosting Technology
Event delegation is also called event agent (from whose perspective). Using event delegation technology can avoid adding event listening to each child node. On the contrary, event listening can be delegated to the parent element, which can improve the performance of binding events
oUl.onclick = function(e){ var ev = e || window.event; // Gets the dom object of the clicked target element var target = ev.target || ev.srcElement; // Determine whether it is a li tag if(target.nodeName == "LI"){ //⭐⭐⭐ Note that the browser has been changed to uppercase //It is not necessary to verify nodeName // Complete business logic alert(target.innerText); } }
4. Event type
1. Ul event (window)
-
window.onload=fn; Last load event
-
window.onunload=fn; Close browser trigger event
-
window.onbeforUnload=fn; Event triggered immediately before closing the browser
-
abort: when the user stops the download process, if the embedded content is not loaded, it will be triggered on the element
-
Error: triggered on the window when JavaScript error occurs, on the element when the image cannot be loaded, and on the element when the content cannot be loaded
-
window.onselect=fn;: Triggered when the user selects a text box
-
window.onresize=fn;: Triggered on the window or frame when the size of the window or frame changes
-
scroll;: Scroll bar scrolling event, triggered by the element that scrolls
-
Implementation of browser window switching detection ⭐: https://www.cnblogs.com/xulinjun/p/11452001.html
visibilitychange property
<script> document.addEventListener('visibilitychange',function(){ //Browser switching event if(document.visibilityState=='hidden') { //State judgment //normal_title=document.title; document.title = 'Title II'; }else { document.title = 'Title I'; } }); </script>
2. Information acquisition of scroll event
- Scroll up and down: document documentElement. scrollTop
- Scroll up and down: document body. scrollTop
- The above two require short circuit writing to prevent compatibility problems
- Left and right is to change top to left
3. Focus event
- blur: triggered when the element loses focus. There is no bubble and no compatibility problem
- Focus: triggered when the element obtains the focus. There is no bubble and no compatibility problem
- Focus in: triggered when the element gets focus, bubbling, IE5 5+,Safari5. 1+,Opera11. 5 +, supported by chrome
- Ditto: when the element is triggered, focus is lost
4. Mouse event
- Left click: Click
- Right click: contextmenu
- Double click: dblclick
- Left click: mousedown
- Left click: mouseup
- Mouse up [^ note 12]: mouseover
- Mouse away [^ note 12]: mouseout
- ⭐ (excluding children) mouse up [^ note 13]: mouseenter
- ⭐ (excluding children) mouse away [^ remark 13]: mouseleave
- Mouse movement event: mousemove
5. Cursor position
Object get event
6. Modify key
Modify mouse events through shift, ctrl, alt, window or cmd. Since users can hardly use shortcut keys and key combinations, they will not be introduced
7,e.button
Mouse button judgment
- Return 0: indicates that the mouse button is not pressed
- Returning to 1: means pressing the left key
- Returning to 2 means pressing the right key
- Return to 3: press the left and right keys at the same time
- Return to 4: press the pulley key
- Return to 5: press the left + pulley key
- Return to 6: press the right + pulley key
- Returning to 8 means pressing three keys
8. Mouse wheel event
ie6 first implements: mousewhere event. The corresponding event object contains a special attribute, wheldelta. When sliding up, it is a multiple of 120 and when sliding down, it is a multiple of - 120
Opera9. It was the opposite before version 5
9. Keyboard events
-
Press: keydown
-
Pop up: keyup
-
Pop up no matter you press: keypress
-
Judgment key code: obtain judgment through e.keyCode
-
Judgment key combination:
- Press the alt key to get true, otherwise get false: altKey
- Press the shift key to get true, otherwise get false: shiftKey
- Press ctrl to get true, otherwise get false: ctrl key
-
In the editable area, enter: textInput: new for DOM3
The input method can be determined through the special attribute inputMethod of its event object
- 0: indicates that the browser is not sure how to enter
- 1: Keyboard input
- 2: Paste
- 3: Put into
- 4: Use IME input
- 5: Form input
- 6: Handwriting input
- 7: Language input
- 8: Combined input of the above methods
- 9: Script input
10. Form event
- Submit form: submit
- Get focus: focus
- Lose focus: blur
- Content changes and loses focus: change
- The value of input changes in real time: input
- input event in lower version IE: onpropertychange
- Prevent submitting events use the block default event: e.preventDefault()
- checkbox judgment: input ckecked||input. checked=true.
11. Encapsulation of events
function bind(ele,type,callback){ tyr{ ele.addEventstener(type,callback,false) }catch(e){ ele.attachEvent("on"+type,callback) } }
- Binding is bind
- Others are unbind
- Object to bind event: ele
- Event type: type
- Callback function for handling events: callback
11. Symbol:
There are also some relatively unpopular events: composite events, change events and HTML5 events. These events are designed and detected for developers and will not be introduced.
12. Device events 🌙
I really can't do this. Due to the continuous release and use of comprehensive screen, great changes are taking place in keys and methods. There are specific modules on jQuery Mobile, so it's impossible to carry out mobile device experiments
13. Form supplement
Most of them have been introduced in html, and only some properties and methods of js are introduced
1. Operating the pasteboard
Opera does not support accessing the pasteboard through JavaScript
- berorecopy: triggered before a complex operation occurs
- copy: triggered when a complex operation occurs
- Before cut: triggered before the cutting operation occurs
- Cut: triggered when a cut operation occurs
- Before paste: triggered before the paste operation occurs
- Paste: triggered when a paste operation occurs
2. Auto switch focus
Active focus: focus()
Judge the word number of input, and add input when the conditions are met Focus() causes the input element that should be obtained to obtain the focus
3. Rich text editing 🌙
iframe tag content compilation
1. Using the contenteditable attribute
You can assign the contenteditable attribute to any element in the page, and then you can edit the element
<div class="editable" id="richedit" contenteditable></div>
You can also turn compilation mode on and off
div.contenteditable=true;//true: open; false: close; Inherit: inherit the parent element
2. Action rich text
document.execCommand() is extremely popular and may not be used for a lifetime. Continue editing later
3. Rich text selection
Use the getSelection() method of the framework (iframe); Continue editing later
14. Canvas drawing 🌙
Most anticipated features
15. Offline application storage problem
1. Offline detection
navigator.onLine; Judge whether the network is connected. Yes, no, false. It was mentioned earlier when introducing navigator
Available. Modifiable assignment
2. Application cache
HTML5's application cache, or appcache for short, means that web applications can be cached and accessed without an Internet connection.
Application caching brings three advantages to applications:
- Offline browsing - users can use them when applications are offline
- Speed - cached resources load faster
- Reduce server load - the browser will only download updated or changed resources from the server.
Detect that the status of the application cache is applicationcache Status, the attribute value is a constant
- 0: no cache
- 1: Idle
- 2: Checking: download the description file and check for updates
- 3: Downloading
- 4: Update completed: it has been downloaded and can be used through swapCache()
There are many related events in the application cache, indicating the change of its state
- checking: triggered when the browser finds updates for the application cache
- Error: an error occurred while looking for updates or downloads
- noupdate: triggered when checking the description file and finding that the file has not changed
- Downloading: triggered when downloading application resources
- progress: it is triggered continuously during the process of file downloading and application caching
- updateready: after the new application is downloaded on the page, it can be triggered through swapCache()
- cached: triggered when the application cache is fully available
3,cookie
1. Request header information
HTTP cookies are usually called cookies directly
When a set cookie occurs, the request header is as follows:
HTTP/1.1 200 OK Content-type: text/html Set-Cookie:name=value;expires=Mon, 22-Jan-20 07:10:24 GMT;domain=.wrox.com //URL encoding is required for all transfers Other-header:other-header-value
Send the information back to the server every time the Cookie HTTP header is added
GET /index.html HTTP/1.1 Cookie: name=value Other-header:other-header-value
2. Number limit
The minimum number of cookie s for low version IE is 20, and the best number for others is no more than 50
The last word count is within 4095B
3. Add, delete, modify and check
1. Add / modify: document Cookie = "key = value [, expiration time]"
If the expiration time is not set, it will expire when the browser is closed by default, and the expiration time is the international coordination time. For China, 8 hours will be subtracted, and the unit is milliseconds
2. Delete: document Cookie = "key = null, one second before the current time"
Cookies cannot be deleted directly and manually. They can only be deleted in advance.
3. Check: document cookie(); Get all cookies and return a string
4. Encapsulated simple cookie function (this is simple and crude, but not the best)
/*jshint esversion: 6 */ //Functions that set or add or modify cookie s (function (){ return function setCookie(key,value,indite){ let date=new Date(); if(indite!=null){ date.setTime(date.getTime()-8*60*60*1000+indite*1000); document.cookie=key+"="+value+";expires="+date; }else{ document.cookie=key+"="+value; } }; })(); //Read specified cookie encapsulation (function (){ return function getCookie(key){ const cookieArr=document.cookie.split(";"); let value=""; cookieArr.forEach(item=>{ if(item.split("=")[0].trim()==key){ value=item.split("=")[1].trim(); } }); return value; }; })(); //Delete cookie encapsulation (function (){ return function delCookie(name){ setCookie(name,null,-1); }; })();
The concept of sub cookie is to store smaller segments of cookies in cookies
4,localstorage
Due to various compatibility and bug problems of other methods, all of them are not introduced. With their strong development, they will be supplemented
1. Local storage
-
The 4k limit of cookie s is lifted, and the storage capacity can reach 5m
-
After accessing the server for the first time, you can send data and store it in the client's browser
-
The lower version of the browser does not support ie8
-
Protected by the same origin policy.
-
Version support detection
if(!window.localStorage){ alert("Please upgrade your browser"); } //Business logic code
2. Add, delete, modify and check
-
Add / modify
localStorage.setItem('name','Qiuxiang'); //Check in localSrotage, and it is also used for overlay creation, that is, modification
-
obtain
let str=localStorage.getItem('name'); let str=localStorage.key(subscript);//Get the value of the specified subscript key, which is not recommended because you also know the specific subscript
-
delete
localStorage.removeItem('name'); localStorage.clear();//Empty all local storage.
3. And json
let obj={ name:'Sister pomegranate', age:12, hobby:'exercise' }; let str=JSON.stringify(obj); localStorage.setItem('info',str);//Save the converted data to local storage let read=localStorage.getItem('info'); console.log(JSON.pares(read));//Read as transfer object
4. storage event
Used to listen for locally stored events
- Domain: the domain name of the changed storage space
- Key: set or delete the key name
- newValue: if it is a set value, it is a new value; null if delete key
- oldValue: the value before the key is changed
document.onstorage();
5. indexedDB database 🌙
Follow up processing
16. AJAX and Comet 🌙
-----------------Relevant contents can be obtained by jumping to the home page
https://blog.csdn.net/weixin_44070254
17. Some functions are better than vscode plug-ins
https://blog.csdn.net/weixin_44070254/article/details/116091809?spm=1001.2014.3001.5501
It's not easy to summarize. I think this blog is helpful for you and recommend collection. Thank you for your attention and praise. Your support for me is the greatest encouragement to continue writing~