ECMAScript 2016 到 2019 的所有新功能
ES2016
Array.prototype.includes()
let array = [1,3,5,7,9,11] // check if the element appears in our Array array.includes(3); //true array.includes(2); //false // add an index as a second parameter array.includes(3,1); //true array.includes(5,4); //false
Exponential operator
//before Math.pow(2,3); //8 //now 2**3 //8
ES2017
padStart() & padEnd()
"hi".padStart(10); // " hi" "hi".padEnd(10); // "hi " //you are not limited to adding blank spaces "hello".padEnd(13," Alberto"); // "hello Alberto"
Object.entries() & Object.values()
const family = {
father: "Jonathan Kent",
mother: "Martha Kent",
son: "Clark Kent",
}
Object.Values(family);
// ["jonathan Kent", "Martha Kent", "Clark Kent"]
Object.entries(family);
// ["father", "Jonathan Kent"]
// ["mother", "Martha Kent"]
// ["son", "Clark Kent"]
Async & Await
function walk(amount) {
return new Promise((resolve, reject) => {
if (amout < 500) {
reject("the value is too small");
}
setTimeout(() => resolve(walked for ${amount}ms), amount);
});
}
//create an async function
async function go() {
//use the keyword to wait for the response
const res = await walk(500);
console.log(res);
const res2 = await walk(900);
console.log(res2);
const res3 = await walk(600);
console.log(res3);
const res4 = await walk(400);
console.log(res4)
}
go();
// you walked for 500ms
// you walked for 900ms
// you walked for 600ms
// uncaught exception: the value is too small
ES2018
Rest / Spread for Objects
let myObj = {
a: 1,
b: 3,
c: 5,
d: 8
}
// we use the rest operator to grab everythong
// else left in the object.
let {a, b, ...z} = myObj;
console.log(a); // 1
console.log(b); // 3
console.log(z); // {c:5, d:8}
// using the spread syntax we cloned our object
let clone = {...myObj};
console.log(clone);
//{a:1, b:3, c:5, d:8}
Lifting tagged template literals restrictions
function tag(strs) {
strs[0] === undefined
strs.raw[0] === "\\unicode and \\u{55}";
}
tag \unicode and \u{55}
// This loosening of the escape sequence restriction
// only applies to tagged
// template literals; untagged templates
// still throw an early error
// for invalid escape sequences:
let bad = escape sequence: \unicode;
// throws early error
Asynchronous iteration
// iterate asynchronously over our data
// using a for-await-of loop.
for wait (const line of readLines(filePath)) {
console.log(line);
}
Promise.prototype.finally()
fetch("your-url")
.then(result => {
// do something with the result
})
.catch(error => {
// do something with the error
})
.finally(() => {
// do something once the promise is finished
})
RegExp features
// s (dotAll) flag for regular expressions
/ foo.bar/s.test('foo\nbar');
// -> true
// RegExp named capture groups
let re = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/u;
let result = re.exec('2015-01-02');
// result.groups.year === '2015';
// result.groups.month === '01';
// RegExp Lookbehind Assertions
// make sure that a pattern is or isn't preceded by another
// RegExp Unicode Property Escapes
const regexGreekSymbol = /\p{Script=Greek}/u;
regexGreekSymbol.test('n');
// - true
ES2019
Array.prototype.flat()
const letters = ['a', 'b', ['c', 'd', ['e', 'f']]]; // default depth of 1 letters.flat(); // ['a', 'b', 'c', 'd', ['e', 'f']] // depth of 2 letters.flat(2); // ['a', 'b', 'c', 'd', 'e', 'f'] // which is the same as executing flat with depth of 1 twice letters.flat().flat(); // ['a', 'b', 'c', 'd', 'e', 'f'] // Flattens recursively until the array contains no nested arrays letters.flat(Infinity) // ['a', 'b', 'c', 'd', 'e', 'f']
Array.prototype.flatMap()
let greeting = ["Greetings from", " ", "Vietnam"];
// let's first try using a normal `map()` function
greeting.map(x => x.split(" "));
// ["Greetings", "from"]
// ["", ""]
// ["Vietnam"]
// flatten the array and map over it
greeting.flatMap(x => x.split(" "))
// ["Greetings", "from", "", "", "Vietnam"]
Object.fromEntries()
const keyValueArray = [
['key1', 'value1'],
['key2', 'value2']
]
// transforms a list of key-value
// pairs into an object
const obj = Object.fromEntries(keyValueArray)
// {key1: "value1", key2: "value2"}
Function.prototype.toString()
function sum(a, b) {
return a + b;
}
// return a string representing
// the source code of the function.
console.log(sum.toString());
// function sum(a, b) {
// return a + b;
// }
String.prototype.trimStart()`/`.trimEnd()
let str = " the string has a lot of whitespace "; str.length; // 42 // remove white space from the beginning of a string str = str.trimStart(); // "this string has a lot of whitespace " str.length; // 38 // // removes white space from the end of a string str = str.trimEnd(); // "this string has a lot of whitespace" str.length; // 35
Symbol.prototype.description
const me = Symbol("Alberto");
// returns the optional description of a `Symbol` Object.
me.description;
// "Alberto"
me.toString()
// "Symbol(Alberto)"
link: https://inspiredwebdev.com/everything-from-es-2016-to-es-2019
pic:
Comments:
Email questions, comments, and corrections to hi@smartisan.dev.
Submissions may appear publicly on this website, unless requested otherwise in your email.