ES7,ES8简单介绍

2017-08-31  本文已影响0人  韩_小文

ES7新特性:

Array.prototype.includes

Array.prototype.includes用法都容易和简单。它是一个替代indexOf,开发人员用来检查数组中是否存在值,indexOf是一种尴尬的使用,因为它返回一个元素在数组中的位置或者-1当这样的元素不能被找到的情况下。所以它返回一个数字,而不是一个布尔值。开发人员需要实施额外的检查。在ES6,要检查是否存在值你需要做一些如下图所示小技巧,因为他们没有匹配到值,Array.prototype.indexOf返回-1变成了true(转换成true),但是当匹配的元素为0位置时候,该数组包含元素,却变成了false

let arr = ['react', 'angular', 'vue']

// WRONG
if (arr.indexOf('vue')) { 
  console.log('Can use vue') 

// Correct
if (arr.indexOf('vue') !== -1) {
  console.log('Can use vue')
}

在ES7中使用includes代码如下:

let arr = ['react', 'angular', 'vue']

// Correct
if (arr.includes('vue')) {
  console.log('Can use vue')
}

还能在字符串中使用includes:

let str = 'Vue Quickly'

// Correct
if (str.toLowerCase().includes('vue')) {  // true
  console.log('Found "vue"')  
}

includes也可以在NaN(非数字)使用。includes第二可选参数fromIndex,允许从特定位置开始寻找匹配。

console.log([1, 2, 3].includes(2)) // === true)
console.log([1, 2, 3].includes(4)) // === false)
console.log([1, 2, NaN].includes(NaN)) // === true)
console.log([1, 2, -0].includes(+0)) // === true)
console.log([1, 2, +0].includes(-0)) // === true)
console.log(['a', 'b', 'c'].includes('a')) // === true)
console.log(['a', 'b', 'c'].includes('a', 1)) // === false)

ES7新特性(1):

指数操作符:
let a = 7 ** 12
let b = 2 ** 7
console.log(a === Math.pow(7,12)) // true
console.log(b === Math.pow(2,7)) // true
let a = 7
a **= 12
let b = 2
b **= 7
console.log(a === Math.pow(7,12)) // true
console.log(b === Math.pow(2,7)) // true

ES8:

Object.values/Object.entries:

Object.values和 Object.entries是在ES2017规格中,它和Object.keys类似,返回数组类型,其序号和Object.keys序号对应。

在ES8 /ES2017之前,需要迭代一个对象的自身属性时候不得不用Object.keys,通过迭代且使用obj[key]获取value值返回一个数组:

let obj = {a: 1, b: 2, c: 3}
Object.keys(obj).forEach((key, index)=>{
  console.log(key, obj[key])
})

Object.values返回对象自身可以迭代属性值(values)为数组类型。我们最好使用Array.prototype.forEach迭代它,结合ES6的箭头函数隐形返回值:

image.png
let obj = {a: 1, b: 2, c: 3}
Object.values(obj).forEach(value=>console.log(value)) // 1, 2, 3

Object.entries: Object.entries 方法则会将某个对象的可枚举属性与值按照二维数组的方式返回,数组中顺序与 Object.values 保持一致

let obj = {a: 1, b: 2, c: 3}
JSON.stringify(Object.entries(obj))
"[["a",1],["b",2],["c",3]]"
let obj222 = [{a: 1}, 'aa', 44]
JSON.stringify(Object.entries(obj222))
"[["0",{"a":1}],["1","aa"],["2",44]]"

使用ES6/ES2015解构:

let obj = {a: 1, b: 2, c: 3}
Object.entries(obj).forEach(([key, value]) => {
 console.log(`${key} is ${value}`)
})
// a is 1, b is 2, c is 3
字符填充函数String.prototype.padStart 和 String.prototype.padEnd

padStart()在开始部位填充,返回一个给出长度的字符串,填充物给定字符串,把字符串填充到期望的长度

console.log('0.00'.padStart(20))             
console.log('10,000.00'.padStart(20))    
console.log('250,000.00'.padStart(20))
                0.00
           10,000.00
          250,000.00

第二个参数,让我们放一些其他的填充字符替代空字符串,一个字符串填充:

console.log('react'.padStart(10, '_'))         // "_____react"
console.log('backbone'.padStart(10, '*'))         // "**backbone"
console.log('vuevuevue'.padStart(3))       // "vuevuevue"  

padEnd顾名思义就是从字符串的尾端右边开始填充。第二个参数,你能实际上用一个任何长度的字符串。例如:

console.log('react'.padEnd(10, ':-)'))         // "react:-):-" is 10
console.log('backbone'.padEnd(10, '*'))         // "backbone**" is 10
console.log('react'.padEnd(3, ':-)'))          //"react"
Object.getOwnPropertyDescriptors

getOwnPropertyDescriptors 函数会返回对象obj所有自身属性描述。这是一个多参数版本的Object.getOwnPropertyDescriptors(obj,propName);该属性必须是对象自己定义而不是继承自原型链

let azatsBooks = {  
  books: ['Vue Quickly'],
  get latest () {
    let numberOfBooks = this.books.length
    if (numberOfBooks == 0) return undefined
    return this.books[numberOfBooks - 1]
  }
}
console.log(Object.getOwnPropertyDescriptors(azatsBooks))

Object
  books: Object
    configurable: true
    enumerable: true
    value: Array[1]
    writable: true
    __proto__: Object
  latest: Object
    configurable: true
    enumerable: true
    get: latest()
    set: undefined
    __proto__: Object
  __proto__: Object

浅拷贝:

Object.create(
  Object.getPrototypeOf(obj),
  Object.getOwnPropertyDescriptors(obj)
)

合并两个对象

Object.defineProperties(
  target,
  Object.getOwnPropertyDescriptors(source)
)
函数参数列表和调用中的尾逗号:

ES8之前:

var f = function(a,
  b,
  c,
  d) { // NO COMMA!
  // ...
  console.log(d)
}
f(1,2,3,'this')

ES8:

var f = function(a,
  b,
  c,
  d,
) { // COMMA? OK!
  // ...
  console.log(d)
}
f(1,2,3,'this')
async 函数

async 函数返回一个 Promise 对象,可以使用 then 方法添加回调函数。当函数执行的时候,一旦遇到 await 就会先返回,等到触发的异步操作完成,再接着执行函数体内后面的语句。

async function getStockPriceByName(name) {
  var symbol = await getStockSymbol(name);
  var stockPrice = await getStockPrice(symbol);
  return stockPrice;
}

getStockPriceByName('goog').then(function (result){
  console.log(result);
});
function timeout(ms) {
  return new Promise((resolve) => {
    setTimeout(resolve, ms);
  });
}

async function asyncPrint(value, ms) {
  await timeout(ms);
  console.log(value)
}

asyncPrint('hello world', 2000);

await 命令后面的 Promise 对象,运行结果可能是 rejected,所以最好把 await 命令放在 try...catch 代码块中。

async function myFunction() {
  try {
    await somethingThatReturnsAPromise();
  } catch (err) {
    console.log(err);
  }
}

// 另一种写法

async function myFunction() {
  await somethingThatReturnsAPromise().catch(function (err){
    console.log(err);
  });
}

await 命令只能用在 async 函数之中,如果用在普通函数,就会报错。

async function dbFuc(db) {
  let docs = [{}, {}, {}];

  // 报错
  docs.forEach(function (doc) {
    await db.post(doc);
  });
}
上一篇下一篇

猜你喜欢

热点阅读