ECMAScript7/8/9/Next

ES7

  • Array.prototype.includes正则表达式

//es5使用indexOf检查数组中是否存在某个元素
let a = [1,2,3,4,5,NaN];
a.indexOf(6);//-1,返回数值类型

// includes
console.log(a.includes(1));//true,布尔类型,对if语句更友好
console.log(a.includes(1,2));//false

//能查找数组中的NaN
console.log(ary1.indexOf(NaN))//-1
console.log(ary1.includes(NaN))//true

//能查找数组中的undefined
var ary1 = new Array(3);
console.log(ary1.indexOf(undefined));//-1
console.log(ary1.includes(undefined))//true复制代码
  • 求幂运算符数组

Math.pow(4,2)===4**2;//true   函数中的中缀形式复制代码

ES8

  • String.prototype.padStart()promise

//从字符串的开头开始填充
//第一个参数,表示填充的目标长度;
//第二个参数可选,表示填充用的字符串
'abc'.padStart(10);         // " abc"
'abc'.padStart(10, "foo");  // "foofoofabc"复制代码
  • String.prototype.padEnd()浏览器

//从字符串的末尾开始填充
//第一个参数,表示填充的目标长度;
//第二个参数可选,表示填充用的字符串
'abc'.padEnd(10);          // "abc "
'abc'.padEnd(10, "foo");   // "abcfoofoof"复制代码
  • Object.values()安全

//返回对象自身属性值的数组
const person = { name: 'Fred', age: 87 }
Object.values(person) // ['Fred', 87]复制代码
  • Object.entries()bash

//将对象的每一个属性和属性值转换成数组
 const person = { name: 'Fred', age: 87 }
 Object.entries(person) // [['name', 'Fred'], ['age', 87]]

 const people = ['Fred', 'Tony']
 Object.entries(people) // [['0', 'Fred'], ['1', 'Tony']]复制代码
  • Object.getOwnPropertyDescriptors()异步

//全部自身属性的描述对象如:configurable, enumerable, writable, get, set and value
var obj1 = { x: 'xxx', y: 1 };
Object.getOwnPropertyDescriptors(obj1);复制代码
  • 结尾逗号async

// 参数定义时function foo(
    param1,
    param2,) {}

// 函数调用时foo(
    'abc',
    'def',);

// 对象中let obj = {
    first: 'Jane',
    last: 'Doe',};

// 数组中let arr = [
    'red',
    'green',
    'blue',];复制代码
  • Async/Awaitide

//当编译器遇到标定的函数中的await关键字时,要暂时中止运行,带到await标定的函数处理完毕后,再进行相应操
做
async function asyncFunc() {
    const result = await otherAsyncFunc();
    console.log(result);
}复制代码
  • SharedArrayBuffer函数

    • 容许在多个 workers 和主线程之间共享 SharedArrayBuffer 对象的字节

    • 能够更快地在 workers 之间共享数据

    • workers 之间的协调变得更简单和更快(与 postMessage() 相比)

    • 请注意,因为可以轻易地利用《边信道(side-channel)读取未受权内存的攻击技术》中提到的Spectre漏洞——一种利用现代 CPU 使用的执行优化功能的新攻击技术, SharedArrayBuffer 功能将在 Chrome 和 FireFox 的新版本中禁用,并将逐渐被全部浏览器禁用

// main.jsconst worker = new Worker('worker.js');
// 要分享的bufferconst sharedBuffer = new SharedArrayBuffer( // (A)
    10 * Int32Array.BYTES_PER_ELEMENT); // 10 elements
// 使用Worker共用sharedBuffer
worker.postMessage({sharedBuffer}); // clone
// 仅限本地使用const sharedArray = new Int32Array(sharedBuffer); // (B)

// worker.js
self.addEventListener('message', function (event) {
    const {sharedBuffer} = event.data;
    const sharedArray = new Int32Array(sharedBuffer); // (A)
    // ···});复制代码
  • Atomics: 安全访问共享数据

  • 正则表达式Named group

let re1 = /(\d{4})-(\d{2})-(\d{2})/;
let result1 = re1.exec('2015-01-02');
console.log(result1);
// [ '2015-01-02', '2015', '01', '02', index: 0, input: '2015-01-02' ]

// ECMAScript 2018
let re2 = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/u;
let result2 = re2.exec('2015-01-02');
console.log(result2);

// ["2015-01-02", "2015", "01", "02", index: 0, input: "2015-01-02",
//    groups: {year: "2015", month: "01", day: "02"}
// ]

console.log(result2.groups.year); // 2015复制代码

ES9

  • 异步迭代器

    • 异步迭代器和常规迭代器的工做方式很是类似,异步迭代器对象的next()方法返回了一个Promise

async function example() {
  // 普通迭代器:
  const iterator = createNumberIterator();
  iterator.next(); // Object {value: 1, done: false}
  iterator.next(); // Object {value: 2, done: false}
  iterator.next(); // Object {value: 3, done: false}
  iterator.next(); // Object {value: undefined, done: true}

  // 异步迭代器:
  const asyncIterator = createAsyncNumberIterator();
  const p = asyncIterator.next(); // Promise
  await p;// Object {value: 1, done: false}
  await asyncIterator.next(); // Object {value: 2, done: false}
  await asyncIterator.next(); // Object {value: 3, done: false}
  await asyncIterator.next(); // Object {value: undefined, done: true}}复制代码
  • Rest(...)/Spread

    • 在ES9中,为对象提供了像数组同样的rest参数和扩展运算符

    • 展开运算符,剩余运算符

const obj = {
  a: 1,
  b: 2,
  c: 3}
  const { a, ...param } = obj;
  console.log(a)     //1
  console.log(param) //{b: 2, c: 3}


function foo({a, ...param}) {
  console.log(a);    //1
  console.log(param) //{b: 2, c: 3}}复制代码
  • Promise.prototype.finally()

//finally的回调总会被执行。
promise
  .then(result => {···})
  .catch(error => {···})
  .finally(() => {···});复制代码
  • 模板字符串修改

    • 移除对 ECMAScript 在带标签的模版字符串中转义序列的语法限制。以前,\u开始一个 unicode 转义,\x开始一个十六进制转义,\后跟一个数字开始一个八进制转义。这使得建立特定的字符串变得不可能,例如Windows文件路径 C:\uuu\xxx\111。

    • 要取消转义序列的语法限制,可在模板字符串以前使用标记函数String.raw。

console.log(`\\uuu\\xx\\11`);

`\u{54}`// "T"
String.raw`\u{54}`// "\u{54}"复制代码
  • Array.prototype.flat()

    • 按照一个可指定的深度递归遍历数组,并将全部元素与遍历到的子数组中的元素合并为一个新数组返回

var arr1 = [1, 2, [3, 4]];
arr1.flat(); 
// [1, 2, 3, 4]

var arr2 = [1, 2, [3, 4, [5, 6]]];
arr2.flat();
// [1, 2, 3, 4, [5, 6]]

var arr3 = [1, 2, [3, 4, [5, 6]]];
arr3.flat(2);
// [1, 2, 3, 4, 5, 6]

//使用 Infinity,可展开任意深度的嵌套数组
var arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]];
arr4.flat(Infinity);
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]复制代码
  • Array.prototype.flatMap()

    • 方法首先使用映射函数映射每一个元素,而后将结果压缩成一个新数组

var arr1 = [1, 2, 3, 4];

arr1.map(x => [x * 2]); 
// [[2], [4], [6], [8]]

arr1.flatMap(x => [x * 2]);
// [2, 4, 6, 8]

// 只会将 flatMap 中的函数返回的数组 “压平” 一层
arr1.flatMap(x => [[x * 2]]);
// [[2], [4], [6], [8]]复制代码
  • Symbol.description

    • 一个只读属性,它会返回 Symbol 对象的可选描述的字符串

console.log(Symbol('desc').description);
// expected output: "desc"复制代码
  • Function.prototype.toString()

    • toString() 方法返回一个表示当前函数源代码的字符串

function sum(a, b) {
  return a + b;
}

console.log(sum.toString());
// expected output: "function sum(a, b) { // return a + b; // }"

console.log(Math.abs.toString());
// expected output: "function abs() { [native code] }"复制代码
  • String.trimStart() & String.trimEnd()

    • trimStart() 方法从字符串的开头删除空格,trimLeft()是此方法的别名。

    • trimEnd() 方法从一个字符串的末端移除空白字符。trimRight() 是这个方法的别名

    • 以前有String.trim()

var greeting = ' Hello world! ';
console.log(greeting.trimEnd());
// expected output: " Hello world!";复制代码
  • Object.fromEntries()

    • 把键值对列表转换为一个对象

const entries = new Map([
  ['foo', 'bar'],
  ['baz', 42]
]);

const obj = Object.fromEntries(entries);

console.log(obj);
// expected output: Object { foo: "bar", baz: 42 }复制代码
  • JSON Superset

    • 在 ES2019 以前不支持转义行分隔符 (\u2028) 和段落分隔符 (\u2029) 字符,而且在解析过程当中会报错: SyntaxError: Invalid or unexpected token

    • JSON 语法由 ECMA-404 定义并由 RFC 7159 永久修复,容许行分隔符 (\u2028) 和段落分隔符 (\u2029) 字符,直接出如今字符串中

const LS = "";
const PS = eval("'\u2029'");// SyntaxError: Invalid or unexpected token复制代码
  • Optional chaining(暂时不支持)

    • JavaScript 的 Optional chaining 在须要深度访问嵌套对象属性时就特别有用。

    • 当咱们在访问对象的属性前,咱们须要用 ?. 操做符来肯定该属性是否存在

const theAddress = secondUser.address && secondUser.address.office;
console.log(theAddress); // undefined

const theAddress = secondUser?.address?.office; 
console.log(theAddress); // undefined

//肯定方法是否存在
const firstUser = users[0]; 
console.log(firstUser.sayName?.()); // 个人名字是 Olagunju Gbolahan
//若是方法名不存在的话,它会简单的返回 undefined
console.log(firstUser.sayOccupation?.()); // undefined复制代码
相关文章
相关标签/搜索
本站公众号
   欢迎关注本站公众号,获取更多信息