Introduction to the
JS component
It consists of three major parts
- ES (JS syntax specification)
- DOM (API for manipulating Web elements)
- BOM (Operating browser API)
What is ES6?
Prior to 2015, ES versions were named as’ ES+ numbers’, with releases up to ES5.1; However, after 2015, the ES version has been renamed as’ ES+ year ‘and updated year by year. Not only has the naming and updating frequency changed, but also ES2015 has introduced many new features and proposed many remedial syntax for JS defects, making JS more robust and more powerful. Therefore, 2015 is a milestone year for JS. In the industry, all ES versions launched in 2015 and later are collectively called ES6, so ES6 is a general term, including ES2015, ES2017, etc
New syntax
Let const statement
Var bug 1, lack of block-level scope 2, can repeatedly declare the same variable in the same scope 3, no constant concept 4, there is a problem with variable contamination in the for loop 5, variable promotion problem 6, in the global definition of the variable is the property of the window object.Copy the code
Let /const was created to address var’s shortcomings
var btns = document.getElementsByTagName("button"); Var I =0; i<btns.length; i++){ btns[i].onclick = function(){ console.log(i); }} for(let I =0; i<btns.length; i++){ btns[i].onclick = function(){ console.log(i); }} // Output the corresponding indexCopy the code
Reasons for the above examples:Var declares variables that are global.The variables declared by let are local
When defining a const constant, note the following: 1. Once declared, it must be assigned; 2. Once assigned, it cannot be changed; 3Copy the code
Globally, variables declared with var are properties of the Window object (as are function declarations). Variables declared with let/const are not properties of the Window object
Template string
A new way to define strings that makes string concatenation easier and supports line breaks
Var oldOneStr = "XXX "; var oldTwoStr = 'bbb'; Let newStr1 = 'BSSS ${name} HHH'; Let newStr2 = 'test who you are';Copy the code
Deconstruction assignment
Extracting values from arrays or objects and assigning values to variables is called deconstruction and is used to simplify code
Before deconstruction
Var name = obj.name, age = obj.age, desc = obj.desc;Copy the code
After the deconstruction
Var obj = {name: "wt", age: 18, desc: obj;Copy the code
Destruct the failed variable and its value will be undefined
Completely deconstruction
Var obj = {name: "wt", age: 18, desc: "thank you"}; var {name, desc, age} = obj; Var arr = [20, 30, 50]; var [a, b, c] = arr;Copy the code
Part of the deconstruction
Var obj = {name: "wt", age: 18, desc: "thank you"}; var {desc} = obj; Var arr = [20, 30, 50]; var [,, c] = arr;Copy the code
Object deconstruction and rename
var {name: titleName} = obj; // Target the objectCopy the code
How to deconstruct multi-layer nesting
Var obj = {name: 'wt', age: 28, ex: {isMerry: true}} var {name, age, ex: {isMerry}} = obj; Var arr = [1, 2, [100, 200, 300]]; var [x,,[,y]] = arrCopy the code
Other applications (exchange variable values)
var str1 = '234',
str2 = '567';
[str1, str2] = [str2, str1];
Copy the code
A simplified way of writing an object
before
var title = "a", desc = "xxx"; Function go(){} var obj = {title: title, go: go, init: function(){}};Copy the code
simplified
var title = "a", desc = "xxx";
function go(){}
var obj = {
title,
desc,
go,
init(){}
};
Copy the code
Abbreviations can be used when the property name of an object is the same as the variable name
Function parameters
The default value
Before practice
function test(a, b, c){
a = a || 0;
b = b || 0;
c = c || 0;
return a+b+c;
}
Copy the code
Now practice
function test(a=0, b=0, c=0){
return a+b+c;
}
Copy the code
deconstruction
Function arguments: array
Function test([a, b, c]){return a+b+c; } test([10, 20, 30]);Copy the code
Function parameters: Object (recommended)
Function test({c, b, d}){console.log(b); function test({c, b, d}){console.log(b); } test({ d: 12, c: '232', b: true })Copy the code
Deconstructing defaults
If the function argument is an object and the assignment is deconstructed, but the function is called without an argument, an error is reported
function test({c, b, d}){ console.log(b); {c, b, d}=null test({}) {c, b, d}=nullCopy the code
As you can see from the above code, we need at least one empty object {} to be passed, but to pass no arguments and avoid syntax errors, we need to use the destruct object default values, as shown below
Function test({a,b}={}){console.log(a,b)} test() // undefinedCopy the code
Although the above method is syntactically correct, I want to deconstruct a and B to have default values without wearing any values, so I also set the default values of the deconstructed object properties, as follows
Function test ({= 0, b = 0} = {} {the console. The log (a, b)} the test () / / 0, 0Copy the code
The above is the final version, but based on the previous knowledge, we also want to deconstruct the renaming (this is a fake requirement), as follows
function test({a:one=1,b:two=2}={}){
console.log(one,two);
}
test();
Copy the code
The remaining parameter Rest is unknown
Before the ES6
function test(){ console.log(arguments); // Function internal default variable, class array} test();Copy the code
After ES6 (Rest arguments replaced arguments)
function test(a, b, ... c){ console.log(c); / / (three, four, five)} the test (1, 2, 3, 4, 5)Copy the code
Rest parameters can only be used in parameters defined by a function. The rest argument can only appear at the end of a function parameter. 3. The rest argument is actually an array of unknown remaining arguments
Combine with deconstruction
let [a, ...rest] = []; / / a = undefined, rest = [] let [rest] a,... = [1, 2, 3]. / / a = 1, rest = [2, 3] / / array function test ([z] c, d,...) {the console. The log (z); / / (three, four, five)} the test ([1, 2, 3, 4, 5]) / / object function testObj ({name, age,... d}){ console.log(d); // {sex:33,go:false} } testObj({ name: 'xx', sex: 33, go: false, age: 18 })Copy the code
Extended operator
The rest parameter is written exactly the same as the rest parameter mentioned above, but has a completely different function. One receive (REST parameter), one put (extension operator)
Extend the array
function test(){ var arr = [1, 2, 3]; console.log(... arr); // Remove the parentheses from array []}Copy the code
Extended string (Is not recommended
)
function test(){ var str = 'abcd'; console.log(... str); // Split string into characters}Copy the code
Extended object
function test(){ var obj = { name: 'wt', age: 18 }; Var newObj = {sex: 'men',... obj }; }Copy the code
The outermost property is a non-complex type and will be copied completely. If it is a complex type (object, array, function), it will share the same set of data with the original object. The code is as follows:
const obj = { name: 'xxx', info: { schoolName: 'bsss' } } const obj1 = { ... obj } obj.name = '2222' obj.info.schoolName = 'woshixiaoxue' console.log(obj1.name); // xxx console.log(obj1.info.schoolName); // woshixiaoxueCopy the code
Usage scenarios
1. Values in arrays are function parameters (values in objects are not function parameters)
function test(a, b, c){ console.log(a,b,c); } let arr = [10,20,30]; test(... arr);Copy the code
2. Array merge
Let arr1 = [1,2,3],arr2 = [2,3,4]; Let arr = [...arr1,...arr2]; / /,2,3,2,3,4 [1]Copy the code
3. String to array
let arr = [...'abcd'];
Copy the code
4. Merge objects
let obj1 = { name: 'ww', age: 18 }; Let obj2 = {name: 'tt', sex: 'male'}; // merge and deduplicate, if there is the same KEY, replace the previous (write order) let newObj = {... obj2,... obj1}; // es6 also provides another API for merging objects. Let newObj = object. assign({}, obj2, obj1);Copy the code
Note: The property value of the merged object (obj1/obj2) will change if the merged object (obj1/obj2) is a reference type. If the merged object is not a reference type, the property value of the merged object (newObj) will not change
Arrow function
Use arrows (=>) to simplify function definitions
The difference between ordinary functions and arrow functions
Normal functions can be defined in three ways (function declarations, function expressions, and anonymous functions), while arrow functions can be defined in two ways (function expressions, and anonymous functions). Normal functions have dynamic this, while arrow functions have static this. The arrow function’s this points to this of the current environment
The statement
// let fn = () => {}; // Anonymous function usage () => {}Copy the code
Pay attention to the point
1, if only one function parameters, can omit the brackets do not write 2, if the function is only a statement in the body, can omit braces don’t write, if the statement is the return, you can even omit the return 3, if there are multiple statements functions in the body, cannot omit braces 4, if the body of the function is only one statement, Return arguments (); return arguments (); return arguments ()
Const test1 = () => console.log(123); // No arguments and only one statement const test1 = () => console.log(123); Const test2 = p => {let a = 1,b = 2; return a+b; }; Const test3 = (a,b) => a+b;Copy the code
Application scenarios
The callback function
SetTimeout (()=>{console.log(123); }, 3000); Let arr = [1,2,3,4]; arr.forEach(item => console.log(item));Copy the code
this
The arrow function does not have its own this. The object attribute uses this to refer to this in the object’s scope
Var obj = {name: 'bb', desc: this.name + 'I'm coming' go: function(){console.log(this.name); // obj.go() where this refers to obj object (recommended)}, come: () => {console.log(this.name); // obj.come() where this points to the outer window}} let BTN = document.getelementById ("#send"); btn.onclick = function(){ setTimeout(function(){ console.log(this); // this points to window}, 2000); setTimeout(()=>{ console.log(this); // this points to BTN (recommended)}, 3000); }Copy the code
Promise
It is a more reasonable and powerful asynchronous programming solution than the traditional solution (callback function)! Promise is an object, more like a container, that holds asynchronous operations
role
Solve the callback hell problem in asynchronous programming, asynchronous code synchronization
Three states
This is a big pity. 3. This operation is postponed 3
The characteristics of
1. The Promise object is unaffected by external influences. The Promise object represents an asynchronous operation. Once the state changes, it will not change again. There are only two situations when the state of the Promise object changes: (1) Pending becomes a pity; (2) Pending becomes the rejected state once it is set, it will not change againCopy the code
When the state changes, you add a callback to the Promise object, and the callback returns the same result immediately. Totally different from the event
grammar
Const p = new Promise(function(resolve, reject){resolve(); // pending --> fulfiled success}else{reject(); // Pending --> Rejected}}); p.then(d => {}).catch(err => {});Copy the code
An array of
Reduce traversal sum
grammar
Let arr = [1, 2, 3]; Let res = arr. Reduce (function(pre, current, index, arr){ Execute this function once // pre refers to the return value of the last time this function was executed // If traversal has initValue for the first time, Pre is initValue (iterated from 0) // Otherwise pre is a value with subscript 0 (iterated from 1) // current Current element iterated return 10; }, initValue); Console. log(res) // The value returned is iterated for the last timeCopy the code
Application scenarios
Sum and product
Const arr =,4,5,6,7 [1]; // let addRes = arr.reduce(function(pre, current, index, arr){return pre+current; }, 0); // let mulRes = arr.reduce(function(pre, current, index, arr){return pre*current; }, 1);Copy the code