That's enough for ES6

1. let、const

1.1 Problems with var

  1. var has scope issues (it pollutes the global scope)
  2. var can be declared repeatedly
  3. var will variable hoist preinterpretation
  4. var cannot define constants

1.2 let and const features

  1. let and const cannot be declared repeatedly
  2. let and const are not declared to the global scope
  3. let and const do not pre-interpret variables
  4. const makes constant declarations (usually constant names are capitalized)

1.3 Give it a try

//1. 作用域
//var
var a = 5;
console.log(window.a); //5

//let、const
let a = 5;
console.log(window.a); //undefined
//有一个问题,let定义的a声明到哪里了呢?欢迎解释(:

//2. 重复声明 
//var 
var a = 5;
var a = 6;

//let、const
let a = 5;
let a = 6; //Identifier 'a' has already been declared 不能重复声明

//3. 预解释
//var
console.log(a); //undefined  相当于 var a;
var a = 5;

//let const
console.log(a)//Uncaught ReferenceError: a is not defined 语法错误,没有预解释
let a = 5;

//4. 常量
//var
var a = 5;
a = 6;

//const
const a = 5;
a = 6;//Uncaught TypeError: Assignment to constant variable. 语法错误

2. Deconstruction

Destructuring is a new feature of ES6, which can directly parse the contents of array objects.

//1.数组解构
let [a1,a2,a3] = [1,2,3]; //a1 = 1; a2 = 2; a3 = 3;

//2.对象解构
let {name,age} = {name:'meteor',age:8}; //name = 'meteor',age = 8;
//let {name:n} = {name:'meteor',age:8};//n = 'meteor' 可以用“:”的形式修改变量名

//3.复杂解构
let [{age}] = [{age:8,name:'xx'},'深圳',[1,2,3]]; //age = 8   注意对象解构

//4.默认赋值
let {age=5} = {age:8,name:'xx'}; //age=8 如果没有age字段 age=5
//常用函数参数给默认值
//以前
function(){var a = a || 5}
//现在
function(a=5){}

3. String

The "`" backticks are added in es6, and ${} in backticks handles template strings.

3.1 Backticks

  1. More Human String Concatenation
let name = 'xx';
let age = 9;
let str = `${name}${age}岁了`;
console.log(str); //xx今年岁了
  1. Simple simulation using regular + eval
let name = 'xx';
let age = 9;
let str = `${name}${age}岁了`;
str = str.replace(/\$\{([^}]+)\}/g, function ($1) {
    return eval(arguments[1]);
})
console.log(str); //xx今年岁了
  1. Template characters with labels
//反引号前使用方法,方法按模版变量把字符串分成两个数组
//第一个为固定值组成的数组 
//第二个值为替换变量组成的数组
let name = 'xx';
let age = 9;
function tag(strArr, ...args) {
    var str = '';
    for (let i = 0; i < args.length; i++) {
        str += strArr[i] + args[i]
    }
    console.log(strArr,args);
    //[ '', '今年', '岁了' ]   [ 'xx', 9 ]
    //
    str += strArr[strArr.length - 1];
    return str;
}
let str = tag`${name}今年${age}岁了`;
console.log(str);

3.2 includes method

//判断字符串中是否包含某个字符串
let str = 'woaini';
str.includes('ai'); //true

3.3 endsWith、startsWith 方法

//判断字符串是否以某一个字符串开始或结束
var a = '1AB2345CD';
console.log(a.startsWith('1A')); //true
a.endsWith('cD') //false

4. Function

4.1 Function parameters can be assigned and destructured

function({a=5}){}

4.2 Arrow functions

  1. If there is only one parameter, the parentheses can be omitted
  2. If you don't write return, you can leave out the curly brackets
  3. no arguments variable
  4. Do not change this pointer
//求和
let sum = (a,b)=>a+b;

5. Arrays

5.1 New methods for arrays

  1. Array.from(); //Convert class array to array
  2. Array.of(); //Create an array
  3. Array.fill();//fill the array
  4. Array.reduce();//The incoming callback is suitable for processing adjacent array elements
  5. Array.filter();//Array filtering
  6. Array.find();//Find the return value
  7. Array.includes();//Determine whether the array has a certain value

5.2 Array.from()

//Array.from();
let arr = Array.from({'0':1,'1':2,length:2});
console.log(arr);//[1,2]

5.3 Array.of()

Array.of(2,3); //[2,3]

5.4 Array.reduce()

[1, 2, 3, 4, 5].reduce((prev, next, index, current) => {
    //prev 如果reduce传入第二个参数,prev为第二个参数;否则prev为数组第一个元素  往后累加
    //next 如果reduce传入第二个参数,next为第数组第一个元素;否则next为数组第二个元素  依次累加
    //index 函数第几次执行1开始
    //current当前数组
    return prev + next;
})
//reduce方法简单实现
Array.prototype.myReduce = function (cb, pre) {
    let prev = pre || this[0];
    for (var i = pre ? 0 : 1; i < this.length; i++) {
        prev = cb(prev, this[i], i, this);
    }
    return prev;
}

5.3 Array.filter();

let result = [1,2,3,4,5].filter(function(item){
    return item>3;
})
console.log(result);//[4,5]
//filter简单实现
Array.prototype.myFilter = function(cb){
    var arr = [];
    for(var i=0; i<this.length; i++){
        var item = this[i];
        if( cb(item) ) arr.push(item);
    }
    return arr;
}

5.4 Array.find();

let result = [1,1,1,2,3].find(function(item){
    return item == 2;
})
console.log(result);//2

6. Objects

6.1 If Key and Value are equal, you can abbreviate

let name = 'xx';
let obj = {name};

6.2 Deconstruction

7. Class

  1. Class defines the class
  2. extends implements inheritance
  3. Support for static methods
  4. constructor construction method
class Parent{
    constructor(name){
        this.name = name;
    }
    getName(){
        return this.name;
    }
    static fn(){
        return 9;
    }
}
class Child extends Parent{
    constructor(name,age){
        super(name);//子类有构造函数必须有super
        this.age = age;
    }
}
let child = new Child('xingxing',9);
console.log(child.getName());//xingxing
console.log(child.name);//xingxing
console.log( Child.fn() );//9

8. Generator

8.1 Use "*" before iterator function name

function *gen(){}

8.2 yield yield

The iterator temporarily suspends execution when it encounters yield, and calls the iterator next method to continue execution

8.3 Give it a try

function *gen(){
    let a = yield 'xx';
    console.log(a);//a
    let b = yield 9;
    console.log(b);
    return b;
}
let it = gen();
console.log(it.next('a'));// value: 'xx', done: false }
console.log(it.next('b'));//{ value: 9, done: false }

8.4 Combining with promise co

let bluebird = require('bluebirld');
let co = require('co');
let fs = require('fs');
let read = bluebird.promisify(fs.readFile);
function *r(){
    let content1 = yield read('./1.txt','utf8'); //内容 ./2.txt
    let content2 = yield read(content1,'utf8');
    return content2;
}
let it = r();
//可以自动迭代generator
co(it).then(function(data){
    console.log(data);
});
//实现异步代码同步化

9. async await

  1. async is used to decorate functions and needs to be used with await
  2. You can only follow promises after await
let bluebird = require('bluebird');
let fs = require('fs');
let read = bluebird.promisify(fs.readFile);
//await 后只能跟promise
async function r(){
    let content1 = await read('./1.txt','utf8');
    let content2 = await read(content1,'utf8');
    return content2;
}
//async返回promise
r().then(function(data){
    console.log(data); 
})

Author: Meteor
Link: https://juejin.im/post/5abf531d6fb9a028dc412419
Source: Nuggets The
copyright belongs to the author. For commercial reprints, please contact the author for authorization, and for non-commercial reprints, please indicate the source.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325669855&siteId=291194637