ES6、ES7的新特性、基本使用以及 async/await的基本使用

ES6、ES7的新特性、基本使用以及 async/await的基本使用
 
ES6常用新特性:
let && const、iterable类型、解构赋值、=>函数、...操作符、类
 
1、let 命令也用于变量声明,但是作用域为局部
{
    let a = 10;
    var b = 1;        
}
在函数外部可以获取到b,获取不到a,因此例如for循环计数器就适合使用let。
 
2、 const用于声明一个常量,设定后值不会再改变
const PI = 3.1415;
PI // 3.1415
PI = 3; //TypeError: Assignment to constant variable.
 
3、 为了统一集合类型,ES6标准引入了新的iterable类型,Array、Map和Set都属于iterable类型,具有iterable类型的集合可以通过新的for … of循环来遍历。
var a = ['A', 'B', 'C'];
var s = new Set(['A', 'B', 'C']);
var m = new Map([[1, 'x'], [2, 'y'], [3, 'z']]);
for (var x of a) { // 遍历Array    alert(x);
}
for (var x of s) { // 遍历Set    alert(x);
}
for (var x of m) { // 遍历Map
    alert(x[0] + '=' + x[1]);
}
 
4、 ES6 允许按照一定模式,从数组和对象中提取值,对变量进行赋值,这被称为解构(Destructuring)。 
例如数组:
let [a, b, c] = [1, 2, 3];
//等同于
let a = 1;
let b = 2;
let c = 3;
 
5、 ES6中新增箭头操作符用于简化函数的写法,操作符左边为参数,右边为具体操作和返回值。
var sum = (num1, num2) => { return num1 + num2; }
//等同于var sum = function(num1, num2) {
    return num1 + num2;
};
箭头函数还修复了this的指向,使其永远指向词法作用域:
var obj = {
    birth: 1990,
    getAge: function () {
        var b = this.birth; // 1990
        var fn = () => new Date().getFullYear() - this.birth; // this指向obj对象
        return fn();
    }
};
obj.getAge(); // 25
 
6、 这个的引入几乎不会用到extend这个函数来。通过它可以将数组作为参数直接传入函数:
var people=['Wayou','John','Sherlock'];
function sayHello(people1,people2,people3){
    console.log(`Hello ${people1},${people2},${people3}`);
}
//改写为
sayHello(...people);//输出:Hello Wayou,John,Sherlock
 
7、ES6提供了更接近传统语言的写法,引入了Class(类)这个概念,作为对象的模板。通过class关键字,可以定义类,与多数传统语言类似。
class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
  toString() {
    return '(' + this.x + ', ' + this.y + ')';
  }
}
 
 ES7新特性
   Array.prototype.includes
   Exponentiation Operator(求幂运算)
 
1、 Array.prototype.includes用法都容易和简单。它是一个替代indexOf,开发人员用来检查数组中是否存在值,indexOf是一种尴尬的使用,因为它返回一个元素在数组中的位置或者-1当这样的元素不能被找到的情况下。所以它返回一个数字,而不是一个布尔值。开发人员需要实施额外的检查。在ES6,要检查是否存在值你需要做一些如下图所示小技巧,因为他们没有匹配到值,Array.prototype.indexOf返回-1变成了true(转换成true),但是当匹配的元素为0位置时候,该数组包含元素,却变成了false。
let arr = ['react', 'angular', 'vue']
 
 
// WRONGif (arr.indexOf('react')) { // 0 -> evaluates to false, definitely as we expected
  console.log('Can use React') // this line would never be executed}
 
 
// Correctif (arr.indexOf('react') !== -1) {
  console.log('Can use React')
}
 
在ES7中使用includes代码如下:
let arr = ['react', 'angular', 'vue']
 
 
// Correctif (arr.includes('react')) {
  console.log('Can use React')
}
 
还能在字符串中使用includes:
let str = 'React Quickly'
 
 
// Correctif (str.toLowerCase().includes('react')) {  // true
  console.log('Found "react"')  
}
 
2、 求幂运算大多数是做一些数学计算,对于3D,VR,SVG还有数据可视化非常有用。在ES6或者早些版本,不得不创建一个循环,创建一个递归函数或者使用Math.pow,如果忘记了什么是指数,当你有相同数字(基数)自相相乘多次(指数)。例如,7的3次方是7*7*7
 
所以在ES6/2015ES,你能使用Math.pow创建一个短的递归箭头函数:
calculateExponent = (base, exponent) => base*((--exponent>1)?calculateExponent(base, exponent):base)
console.log(calculateExponent(7,12) === Math.pow(7,12)) // true
console.log(calculateExponent(2,7) === Math.pow(2,7)) // true
 
现在在ES7 /ES2016,以数学向导的开发者可以使用更短的语法:
let a = 7 ** 12
let b = 2 ** 7
console.log(a === Math.pow(7,12)) // true
console.log(b === Math.pow(2,7)) // true
 
ES8的异步函数(或者async/await)
 
异步函数(或者async/await)特性操作是Promise最重要的功能。这种想法是为了在写异步代码中简化它,因为人类大脑最讨厌这种平行非序号思维了。它只是不会演变这种方式。本来以为Promise的到来已经是摆脱node异步的福音了,在ES8,异步函数是那么给力。开发者定义一个asyc函数里面不包含或者包含await 基于Promise异步操作。在这引擎之下一个异步函数返回一个Promise,无论无何你在任何地方不会看到这样的一个词Promise。
例如,在ES6中我们可以使用Promise,Axios库向GraphQL服务器发送一个请求:
 
axios.get(`/q?query=${query}`)
  .then(response => response.data)
  .then(data => {
    this.props.processfetchedData(data) // Defined somewhere else  })
  .catch(error => console.log(error))
 
任何一个Promise库都能兼容新的异步函数,我们可以使用同步try/catch做错误处理
async fetchData(url) => {
  try {
    const response = await axios.get(`/q?query=${query}`)
    const data = response.data
    this.props.processfetchedData(data)
  } catch (error) {
    console.log(error)
  }
}
 
异步函数返回一个Promise,所以我们像下面可以继续执行流程:
async fetchData(query) => {
  try {
    const response = await axios.get(`/q?query=${query}`)
    const data = response.data
    return data
  } catch (error) {
    console.log(error)
  }
}
fetchData(query).then(data => {
  this.props.processfetchedData(data)
})
 
有了 async/await,我们的代码执行异步看起来像执行同步一样。可以从头到尾读起来非常简单和易懂,因为出现结果顺序和函数题中从头到尾顺序一样啊!
原文地址:https://www.cnblogs.com/BySee1423/p/13150710.html