Common ES6 features
Flexible use of ES6+ syntax in daily project development can reduce a lot of development time, improve work efficiency. There are many new features available in the ES6 release, so here are some common ES6+ features used in projects:
- let / const
- Arrow function
- Deconstruction assignment
- The default parameters
- Extended operator
- class
- string
- An array of
- Promise
Var, let, const
The application of var
- You can repeat the declaration
var a=12 var a=6 alert(a); // The result is 6Copy the code
- Can’t define a constant
//var
var a = 5;
a = 6;
Copy the code
- There is no block-level scope
if(true){ var a=12 } alert(a); // The result is 12Copy the code
- Will variable promote pre-interpretation
console.log(a); Var a var a = 52Copy the code
Example of block-level scoped var
<script>
window.onload=function(){
var aBtn=document.getElementsByTagName('input')
for(var i=0; i<aBtn.length; i++){ aBtn[i].onclick=function(){
alert(i);
}
}
}
</script>
</head>
<body>
<input type="button" value="Monday">
<input type="button" value="Tuesday">
<input type="button" value="Wednesday">
</body>
Copy the code
The printout results in a 3 for each of the three buttons, indicating that var has no block-level scope
So this code down here has been modified to print out three buttons that are 0, 1, and 2
<script>
window.onload=function(){
var aBtn=document.getElementsByTagName('input')
for(leti=0; i<aBtn.length; i++){ (function(i){
aBtn[i].onclick=function(){
alert(i);
};
})(i)
}
}
</script>
</head>
<body>
<input type="button" value="Monday">
<input type="button" value="Tuesday">
<input type="button" value="Wednesday">
</body>
Copy the code
The application of the let
- Cannot duplicate declaration
let a=5
leta=10 alert(a); // An error occurs because the same variable cannot be declared twiceCopy the code
- You can modify
//letIs a definition variable that can be modifiedletA =12 a=20 alert(a)// Print result a=20Copy the code
- There are block-level scopes
if(true) {leta=12; } alert(a); // A is not definedCopy the code
- Variables are not preinterpreted
Console. log(a)//Uncaught ReferenceError: A is not defined syntax error, no pre-explanationlet a = 52
Copy the code
The case of a block-level scoped LET
We can solve the above problem by using let directly, making the three buttons pop up with 0, 1, 2
<script>
window.onload=function(){
var aBtn=document.getElementsByTagName('input')
for(leti=0; i<aBtn.length; i++){ aBtn[i].onclick=function(){
alert(i);
}
}
}
</script>
</head>
<body>
<input type="button" value="Monday">
<input type="button" value="Tuesday">
<input type="button" value="Wednesday">
</body>
Copy the code
The application of the const
- Cannot duplicate declaration
const a=5 const a=10 alert(a); // An error occurs because the same variable cannot be declared twiceCopy the code
- Do not modify
Const a=12; // Const is a defined constant. a=5; alert(a); // This will cause an error and cannot be modifiedCopy the code
- There are block-level scopes
if(true){ const a=12; } alert(a); // A is not definedCopy the code
- Variables are not preinterpreted
Console. log(a)//Uncaught ReferenceError: A is not defined syntax error, no pre-explanationlet a = 52
Copy the code
Arrow function
Note the following when using arrow functions:
-
If there is only one argument, () can be saved
-
If there is only one return, {} can be omitted
Note: The arrow function shares the same this as the surrounding code, which should help you solve the this pointing problem
Normal functions and arrow functions are written differently
// Normal function 1function show(){} // Arrow function 1letShow =()=>{} // Common function 2function// Arrow function 2 ()=>{}Copy the code
Deconstruction assignment
Extracting values from arrays and objects and assigning values to variables is called deconstruction, which can be used directly with an attribute of the object rather than in the form of attribute access.
Ordinary assignment
// Plain assignmentletArr = [1, 2, 3]let a=arr[0]
let b=arr[1]
letC = arr [2] the console. The log (a, b, c) / / 1, 2, 3Copy the code
Gets the value in the array
// Get the values in the arraylet[a, b, c] = [1, 2, 3]. The console log (a, b, c) / / 1, 2, 3 / / get the values in the arraylet[a, b] = [123, 23] the console, log (a, b) / / 123 23Copy the code
Gets the value in the object
// Get the value in the objectlet {a,c,d}={a:12,c:5,d:6}
console.log(a,c,d)
Copy the code
Complex deconstruction
// Complex deconstructionlet[{a, b}, [n1, n2 and n3], num, STR] = [{4} a: 12, b:,,3,6 [2], 787,'abcdes'] console.log(a,b,n1,n2,n3,num, STR) // Complex destructlet[json, arr, num, STR] = [{4} a: 12, b:,,3,6 [2], 787,'abcdes']
console.log(json,arr,num,str)
Copy the code
The default parameters
$('#div1').animate({width:'200px'});
$('#div1').animate({width:'200px'}, 1000);Copy the code
functionShow (a,b=5,c=12){console.log(a,b,c)} show(99)Copy the code
Extended operator
- Collect the remaining parameters
functionshow(a,b,... The args) {alert (args)} show (12,12,34,3,2,4,28) / / print out the result is 34,3,2,4,28 (... Args must be at the back)Copy the code
- An array of
// A normal functionfunctionshow(a,b,c){ alert(a); alert(b); Alert (c)} show(1,2,3)// The printed result pops up 1, pops up 2, pops up 3letArr1 = [1, 2, 3]letArr2 = [5, 6]let arr=[...arr1,...arr2];
alert(arr)
Copy the code
functionshow(... args){ fn(... args); }functionFn (a,b){alert(a+b)} show(12,5)// pop-up 17Copy the code
An array of
The map example
// Example 1 [45,78,278,890] [{name:'one',level:0,role:9},
{name:'two',level:0,role:8},
{name:'three',level:0,role:7},
{name:'four',level:0,role:6},letArr =,5,8 [12];let result = arr.map((item)=>{
returnitem*2; }) alert(result)//24,10,16letArr =,5,8 [12];letresult = arr.map(item=>item*2); / / 24,10,16 alert (result)Copy the code
Reduce example
Example 1, calculate the averageletScore =,12,34,23,45,55 [89];let result = score.reduce(function(tmp,item,index){
returntmp+item; }) alert(result/score.length)//43(result/score.lengthletArr =,67,67,889,97 [12];let result=arr.reduce(function(tmp,item,index){
if(index! =this.length-1){// Not for the last timereturn tmp+item;
}else{// Last timereturn(tmp+item) } }) alert(result); / / 1132Copy the code
The filter example
1 / / examplesletArr =,5,8,99,67,87 [12];let result=arr.filter(item=>{
if(item%3==0){
return true;
}else{
return false; }}); alert(result); //12,99,87letArr =,5,8,99,67,87 [12];letresult=arr.filter(item=>{ alert(item%3==0); }); // Pop up a Boolean valueCopy the code
The forEach example
letArr =,3,45,6,566 [12]; arr.forEach((item,index)=>{ alert(index+':'+item)//0:12 1:3 2:45 3:6 4:566
})
Copy the code
string
Template string
When you need to concatenate strings, try to use template strings. Template strings can make the concatenation of strings more concise and intuitive
- Do not use template strings
var name = 'The weather today is ' + sun + ' ' + rain + '. '
Copy the code
- Using template Strings
var name = `The weather today is ${sun} ${rain}. `Copy the code
StartsWith example
let str='git://www.baidu.com/23448';
if(str.startsWith('http://')){
alert('Ordinary address');
}else if(str.startsWith('https://')){
alert('Encrypted address');
}else if(str.startsWith('git://')){
alert('git address');
}else{
alert('other'); } / / git addressCopy the code
EndsWith example
let str='1.jpg';
if(str.endsWith('.txt')){
alert('File text');
}else if(str.endsWith('.jpg')){
alert('JPG images');
}else{
alert('other'} / / JPG imagesCopy the code
promise
What is asynchronous programming?
-
Getting data from the server is called asynchronous programming
-
Reading files from Node.js is also asynchronous
The understanding of the promise
I’ll give you a result after a certain amount of time.
When is it used over a period of time?
Asynchronous operation
Asynchronous refers to tasks that may take a long time to produce results, such as network requests and reading local files
What do basic promises look like?
The code is as follows:
index.js
new Promise((resolve, reject) => {
setTimeout(() => {
resolve(1)
})
}).then(value => {
console.log('value',value)
},reason => {
console.log('reason',reason)
})
Copy the code
Running results:
value 1
Copy the code
Native Promise happens when its arguments are not functions, right?
The code is as follows:
index.js
new Promise(1)
Copy the code
promise.js
Class Promise {constructor(executor){//if(typeof executor ! = ='function'){
throw new TypeError('Promise resolver ${executor} is not a function')}}}Copy the code
Running results:
Promise resolver 1 is not a function
Copy the code
This is a basic promise
The following code
index.js
new Promise((resolve, reject) => {
console.log('Good morning! ')
resolve(1)
})
Copy the code
promise.js
Class Promise {constructor(executor){//if(typeof executor ! = ='function'){
throw new TypeError('Promise resolver ${executor} is not a function')
}
const resolve = function (){
}
const reject = function (){
}
executor(resolve,reject)
}
}
Copy the code
Running results:
Good morning!Copy the code
Check out this step-by-step guide to implementing the Promise/A+ specification
generator
Generator function
Iterator function names preceded by *
//generator a generator functionfunction *show2() {
console.log('1')
yield
console.log('2')}letGenObj = show2() genobj.next () // 1 genobj.next () // 2 genobj.next () //Copy the code
yield
The iterator suspends execution at yield and calls the iterator next method to continue execution
- Yield can pass a parameter
//yield can be used to pass parametersfunction *show(){
alert('a'); //alet a=yield;
alert('b'); //b alert(a)//5 }let gen=show();
gen.next(12);
gen.next(5);
Copy the code
- Yield can return
/ / yield returnsfunction *show(){
alert('a');
yield 12;
alert('b');
return 55;
}
let gen=show();
letres1=gen.next(); console.log(res1); //{value:12,done:false}
letres2=gen.next() console.log(res2); //{value:55,done:true} The result of the last step depends onreturn
Copy the code
conclusion
The above examples are some of the new ES6 features that are commonly used in corporate projects, and using these apis wisely will allow us to do more with less development time.