ECMAScript 2016,2017,和2018中新增功能

ECMAScript 2016

1.Array.property.includes() indexOf()不支持查找NaN,includes支持。

2.7**2 指数运算符,结果为49

ECMAScript 2017

1.Object.values() 返回Object自身属性的所有值,排除原型链中的所有值。

2.Object.entries() 以数组方式返回keys和values。

遍历

const obj = { foo: 'bar', baz: 42 };
console.log(Object.entries(obj)); // [ ['foo', 'bar'], ['baz', 42] ]

const obj = { a: 5, b: 7, c: 9 };
for (const [key, value] of Object.entries(obj)) {
   console.log(`${key} ${value}`); // "a 5", "b 7", "c 9"
}
Object.entries(obj).forEach(([key, value]) => {
    console.log(`${key} ${value}`); // "a 5", "b 7", "c 9"
});
View Code

生成Map

const obj = { foo: 'bar', baz: 42 };
const a = Object.entries(obj);
var b= new Map(a)
// {"foo" => "bar", "baz" => 42}
View Code

3.String Padding

向字符串String.proptotype.padStart和String.prototype.padEnd添加了两个实例方法--他们允许在原始字符串的开始或是结尾附加、预先添加空字符串或是其他字符串。

'5'.padStart(10) // '          5'
'5'.padStart(10, '=*') //'=*=*=*=*=5'
'5'.padEnd(10) // '5         '
'5'.padEnd(10, '=*') //'5=*=*=*=*='
View Code
//ES2017
//如果你有一个不同长度的项目列表,并希望格式化它们的显示目的,你可以使用padStart
const formatted = [0, 1, 12, 123, 1234, 12345].map(num => 
    num.toString().padStart(10, '0') // 添加 0 直到长度为 10
);
console.log(formatted);
//打印
// [
//     '0000000000',
//     '0000000001',
//     '0000000012',
//     '0000000123',
//     '0000001234',
//     '0000012345',
// ]    
View Code
const cars = {
  '🚙BMW': '10',
  '🚘Tesla': '5',
  '🚖Lamborghini': '0'
}
Object.entries(cars).map(([name, count]) => {
  //padEnd appends ' -' until the name becomes 20 characters
  //padStart prepends '0' until the count becomes 3 characters.
  console.log(`${name.padEnd(20, ' -')} Count: ${count.padStart(3, '0')}`)
});
//打印结果..
// 🚙BMW - - - - - - -  Count: 010
// 🚘Tesla - - - - - -  Count: 005
// 🚖Lamborghini - - -  Count: 000
View Code
'heart'.padStart(10, "❤️");
22:10:05.595 "❤️❤️❤heart"
View Code

4.Object.getOwnPropertyDescriptors

此方法返回给定对象的所有属性的所有详细信息(包括 get``set 方法). 添加这个的主要动机是允许浅拷贝/克隆一个对象到另一个对象中,这个对象也拷贝getter和setter函数,而不是Object.assign。Object.assign浅克隆除原始源对象的getter和setter函数以外的所有详细信息。

var Car = {
    name: 'BMW',
    price: 1000000,
    set discount(x) {
        this.d = x;
    },
    get discount() {
        return this.d;
    },
};
//使用Object.defineProperties将Car的属性复制到ElectricCar2
//并使用Object.getOwnPropertyDescriptors提取Car的属性
const ElectricCar2 = Object.defineProperties({}, Object.getOwnPropertyDescriptors(Car));
//打印ElectricCar2对象“discount”属性的详细信息
console.log(Object.getOwnPropertyDescriptor(ElectricCar2, 'discount'));
//prints..
// { get: [Function: get],
//   set: [Function: set], 
//   enumerable: true,
//   configurable: true 
// }
// 请注意,getter和setter存在于ElectricCar2对象中,用于'discount'属性!
View Code

5.尾随逗号

6.Async/Await

//ES2015 Promise
function getAmount(userId) {
    getUser(userId)
        .then(getBankBalance)
        .then(amount => {
            console.log(amount);
        });
}

****************************

//ES2017
async function getAmount2(userId) {
    var user = await getUser(userId);
    var amount = await getBankBalance(user);
    console.log(amount);
}
function getUser(userId) {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve('john')
        }, 1000)
    });
}
function getBankBalance(user) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            if(user == 'john') {
                resolve('$1,000');
            } else {
                reject(unknown user);
            }
        }, 1000)
    });
}
View Code
/异步函数本身返回一个Promise
async function doubleAndAdd(a, b) {
    a = await doubleAfterlSec(a);
    b = await doubleAfterlSec(b);
    return a + b;
}
//用法
doubleAndAdd(1, 2).then(console.log);
function doubleAfterlSec(param) {
    return new Promise (resolve => {
        setTimeout(resolve(param * 2), 1000);
    });
}     
View Code
//异步函数本身返回一个Promise
async function doubleAndAdd(a, b) {
    //注意:这边使用 Promise.all
    //注意到使用数组解构,捕获结果
    [a, b] = await Promise.all([doubleAfterlSec(a), doubleAfterlSec(b)]);
    return a + b;
}
//用法
doubleAndAdd(1, 2).then(console.log);
function doubleAfterlSec(param) {
    return new Promise (resolve => {
        setTimeout(resolve(param * 2), 1000);
    });
}    
View Code
// 1. 使用 try catch 
async function doubleAndAdd(a, b) {
    try {
        a = await doubleAfterlSec(a);
        b = await doubleAfterlSec(b);
    } catch (e) {
        return NaN; // return something
    }
    return a + b;
}
// 用法 
doubleAndAdd('one', 2).then(console.log) //NaN
doubleAndAdd(1, 2).then(console.log) // 6
function doubleAfterlSec(param) {
    return new Promise((resolve, reject) => {
        setTimeout(function() {
            let val = param * 2;
            isNaN(val) ? reject(NaN) : resolve(val);
        }, 1000);
    });
}
View Code
//因为异步/等待返回一个Promise,我们可以捕捉整个函数的错误
async function doubleAndAdd(a, b) {
 a = await doubleAfter1Sec(a);
 b = await doubleAfter1Sec(b);
 return a + b;
}
//用法
doubleAndAdd('one', 2)
.then(console.log)
.catch(console.log); //use "catch"
function doubleAfter1Sec(param) {
 return new Promise((resolve, reject) => {
  setTimeout(function() {
   let val = param * 2;
   isNaN(val) ? reject(NaN) : resolve(val);
  }, 1000);
 });
}
View Code

2018-06-23  我尝试了改写之前的项目,使用async/await让我的coding优雅了。

ECMAScript 2018

1.共享内存和原子

2.标记字面量

在标记字面量中,可以编写一个函数来接收字符串文字的硬编码部分,然后从该自定义函数中返回所需的任何内容。

链接

 

posted @ 2018-04-24 21:47  Merrys  阅读(795)  评论(0编辑  收藏  举报