What features does ecmascript have?

青灯夜游
Release: 2022-01-05 11:13:11
Original
1825 people have browsed it

The characteristics of ecmascript are: 1. class (class); 2. Modularity; 3. Arrow function; 4. Template string; 5. Destructuring assignment; 6. Extension operator; 7. Promise; 8 , let and const; 9. Exponential operator "**"; 10. "async/await" and so on.

What features does ecmascript have?

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

What is ECMAScript

ECMAScript is a scripting programming language standardized by ECMA International (formerly the European Computer Manufacturers Association) through ECMA-262.

Ecma International (Ecma International) is an international membership system information and telecommunications standards organization. Before 1994, it was called the European Computer Manufacturers Association. Because of the internationalization of computers, the organization's standards involve many other countries, so the organization decided to change its name to show its international nature. The name is no longer an acronym.

Different from national government standards agencies, Ecma International is a corporate membership organization. The organization's standardization process is more commercial, claiming that this mode of operation reduces bureaucratic pursuit of results.

In fact, Ecma International is responsible for the formulation of many standards, such as the following specifications. You can see that there are our protagonists today, the ECMAScript specification, the C# language specification, the C/CLI language specification, etc.

ECMAScript Relationship with JavaScript

In November 1996, Netscape, the creator of JavaScript, decided to submit JavaScript to the standardization organization ECMA. It is hoped that this language will become an international standard. The following year, ECMA released the first version of Standard Document 262 (ECMA-262), which stipulated the standard for browser scripting language and called this language ECMAScript. This version is version 1.0.

This standard has been developed for the JavaScript language from the beginning, but there are two reasons why it is not called JavaScript. One is trademark. Java is a trademark of Sun. According to the licensing agreement, only Netscape can legally use the name JavaScript, and JavaScript itself has been registered as a trademark by Netscape. Second, I want to show that the developer of this language is ECMA, not Netscape, which will help ensure the openness and neutrality of this language.

Therefore, the relationship between ECMAScript and JavaScript is that the former is a specification of the latter, and the latter is an implementation of the former.

The relationship between ES6 and ECMAScript 2015

The word ECMAScript 2015 (ES2015 for short) is also often seen. How does it relate to ES6?

After ECMAScript version 5.1 was released in 2011, work began on version 6.0. Therefore, the original meaning of the word ES6 refers to the next version of the JavaScript language.

However, because this version introduces too many grammatical features, and during the formulation process, many organizations and individuals continue to submit new features. It quickly became clear that it would not be possible to include all the features that would be introduced in one release. The conventional approach is to release version 6.0 first, then version 6.1 after a while, then version 6.2, version 6.3, and so on.

The Standards Committee finally decided that the standard would be officially released in June every year as the official version of that year. In the following time, changes will be made based on this version. Until June of the next year, the draft will naturally become the new year's version. This way, the previous version number is not needed, just the year stamp.

Therefore, ES6 is both a historical term and a general term. It means the next generation standard of JavaScript after version 5.1, covering ES2015, ES2016, ES2017, etc., while ES2015 is the official name, specifically referring to The official version of the language standard released that year.

ECMAScript History

In November 1996, Netscape submitted JS to the international standards organization ECMA. Now the language can become an international standard. standards.
In 1997, ECMAScript version 1.0 was launched. (In this year, ECMA released the first version of Standard Document No. 262 (ECMA-262), which stipulated the standard for browser scripting language and called this language ECMAScript, which is the ES1.0 version.)
1998 In June of this year, ES version 2.0 was released.
In December 1999, ES version 3.0 was released and became the common standard for JS and received widespread support.
In October 2007, the draft version 4.0 of ES was released.
In July 2008, ECMA decided to terminate the development of ES 4.0 due to too great differences between the parties. Instead, a small set of improvements to existing functionality will be released as ES 3.1. However, it was renamed ES version 5.0 shortly after returning;
In December 2009, ES version 5.0 was officially released.

In June 2011, ES version 5.1 was released and became an ISO international standard (ISO/IEC 16262:2011).
In March 2013, the ES 6 draft ended, and no new features will be added.
In December 2013, the ES 6 draft was released.
In June 2015, the official version of ES 6 was released.

From now on, an official version will be released in June every year, so the latest version is ES12 released in June 2021.

New features in each version of ECMAScript

New features in ES6

1, class

ES6 introduces classes to make object-oriented programming in JavaScript simpler and easier to understand.

class Student {
  constructor() {
    console.log("I'm a student.");
  }
 
  study() {
    console.log('study!');
  }
 
  static read() {
    console.log("Reading Now.");
  }
}
 
console.log(typeof Student); // function
let stu = new Student(); // "I'm a student."
stu.study(); // "study!"
stu.read(); // "Reading Now."
Copy after login

2. Modularization

ES5 supports native modularization, and modules are added as an important component in ES6. The functions of the module mainly consist of export and import. Each module has its own separate scope. The mutual calling relationship between modules is to specify the interface exposed by the module through export, and to reference the interfaces provided by other modules through import. At the same time, a namespace is created for the module to prevent naming conflicts of functions.

export function sum(x, y) {
  return x + y;
}
export var pi = 3.141593;
Copy after login
import * as math from "lib/math";
alert("2π = " + math.sum(math.pi, math.pi));

import {sum, pi} from "lib/math";
alert("2π = " + sum(pi, pi));
Copy after login

3. Arrow function

=> is not only the abbreviation of the keyword function, it also brings other benefits. The arrow function shares the same this with the code surrounding it, which can help you solve the problem of this pointing. For example, var self = this; or var that =this refers to the surrounding this mode. But with =>, this pattern is no longer needed.

() => 1

v => v+1

(a,b) => a+b

() => {
  alert("foo");
}

e => {
  if (e == 0){
    return 0;
  }
  return 1000/e;
}
Copy after login

4. Template string

ES6 supports template strings, making string splicing more concise and intuitive.

//不使用模板字符串
var name = 'Your name is ' + first + ' ' + last + '.'
//使用模板字符串
var name = `Your name is ${first} ${last}.`
Copy after login

In ES6, string concatenation can be completed by ${}, just put the variables in curly brackets.

5. Destructuring assignment

The destructuring assignment syntax is a JavaScript expression that can quickly extract values ​​from an array or object and assign them to defined variables.

// 对象
const student = {
    name: 'Sam',
    age: 22,
    sex: '男'
}
// 数组
// const student = ['Sam', 22, '男'];

// ES5;
const name = student.name;
const age = student.age;
const sex = student.sex;
console.log(name + ' --- ' + age + ' --- ' + sex);

// ES6
const { name, age, sex } = student;
console.log(name + ' --- ' + age + ' --- ' + sex);
Copy after login

6. Extension operator

The extension operator... can expand the array expression or string at the syntax level during function call/array construction; it can also When constructing an object, expand the object expression in a key-value manner.

//在函数调用时使用延展操作符
function sum(x, y, z) {
  return x + y + z
}
const numbers = [1, 2, 3]
console.log(sum(...numbers))

//数组
const stuendts = ['Jine', 'Tom']
const persons = ['Tony', ...stuendts, 'Aaron', 'Anna']
conslog.log(persions)
Copy after login

7. Promise

Promise is a solution for asynchronous programming, which is more elegant than the traditional solution callback. It was first proposed and implemented by the community. ES6 wrote it into the language standard, unified its usage, and provided Promise objects natively.

const getJSON = function(url) {
  const promise = new Promise(function(resolve, reject){
    const handler = function() {
      if (this.readyState !== 4) {
        return;
      }
      if (this.status === 200) {
        resolve(this.response);
      } else {
        reject(new Error(this.statusText));
      }
    };
    const client = new XMLHttpRequest();
    client.open("GET", url);
    client.onreadystatechange = handler;
    client.responseType = "json";
    client.setRequestHeader("Accept", "application/json");
    client.send();

  });

  return promise;
};

getJSON("/posts.json").then(function(json) {
  console.log('Contents: ' + json);
}, function(error) {
  console.error('出错了', error);
});
Copy after login

8. let and const

Before, JS did not have block-level scope. Const and let filled this convenient gap. Both const and let Block-level scope.

function f() {
  {
    let x;
    {
      // 正确
      const x = "sneaky";
      // 错误,常量const
      x = "foo";
    }
    // 错误,已经声明过的变量
    let x = "inner";
  }
}
Copy after login

ES7 new features

1. Array.prototype.includes()

includes() function is used to Determines whether an array contains a specified value, if so it returns true, otherwise it returns false.

[1, 2, 3].includes(-1)                   // false
[1, 2, 3].includes(1)                    // true
[1, 2, 3].includes(3, 4)                 // false
[1, 2, 3].includes(3, 3)                 // false
[1, 2, NaN].includes(NaN)                // true
['foo', 'bar', 'quux'].includes('foo')   // true
['foo', 'bar', 'quux'].includes('norf')  // false
Copy after login

2. Exponential operator

The exponent operator** was introduced in ES7, **has calculation results equivalent to Math.pow(...) . Use the exponentiation operator **, just like the , - and other operators.

//之前的版本
Math.pow(5, 2)

// ES7
5 ** 2
// 5 ** 2 === 5 * 5
Copy after login

ES8 new features

1. async/await

The asynchronous function returns an AsyncFunction object and passes through the event loop Asynchronous operations.

const resolveAfter3Seconds = function() {
  console.log('starting 3 second promsise')
  return new Promise(resolve => {
    setTimeout(function() {
      resolve(3)
      console.log('done in 3 seconds')  
    }, 3000)  
  })  
}

const resolveAfter1Second = function() {
  console.log('starting 1 second promise')
  return new Promise(resolve => {
      setTimeout(function() {
        resolve(1) 
        console.log('done, in 1 second') 
      }, 1000)
  })  
}

const sequentialStart = async function() {
  console.log('***SEQUENTIAL START***')
  const one = await resolveAfter1Second()
  const three = await resolveAfter3Seconds()

  console.log(one)
  console.log(three)
}

sequentialStart();
Copy after login

2. Object.values()

Object.values() is a new function similar to Object.keys(), but returns Are all values ​​of the Object's own properties, excluding inherited values.

const obj = { a: 1, b: 2, c: 3 }
//不使用 Object.values()
const vals = Object.keys(obj).map((key) => obj[key])
console.log(vals)
//使用 Object.values()
const values = Object.values(obj1)
console.log(values)
Copy after login

It can be seen from the above code that Object.values() saves us the steps of traversing keys and obtaining value based on these keys.

3. Object.entries()

The Object.entries() function returns an array of key-value pairs of the enumerable properties of the given object itself.

//不使用 Object.entries()
Object.keys(obj).forEach((key) => {
  console.log('key:' + key + ' value:' + obj[key])
})
//key:b value:2

//使用 Object.entries()
for (let [key, value] of Object.entries(obj1)) {
  console.log(`key: ${key} value:${value}`)
}
//key:b value:2
Copy after login

4. String padding

In ES8, String has added two new instance functions, String.prototype.padStart and String.prototype.padEnd, which allow null characters to be String or other string added to the beginning or end of the original string.

console.log('0.0'.padStart(4, '10'))
console.log('0.0'.padStart(20))

console.log('0.0'.padEnd(4, '0'))
console.log('0.0'.padEnd(10, '0'))
Copy after login

5. Object.getOwnPropertyDescriptors()

The Object.getOwnPropertyDescriptors() function is used to get the descriptors of all the own properties of an object. If there are no own properties , then an empty object is returned.

let myObj = {
  property1: 'foo',
  property2: 'bar',
  property3: 42,
  property4: () => console.log('prop4')  
}

Object.getOwnPropertyDescriptors(myObj)

/*
{ property1: {…}, property2: {…}, property3: {…}, property4: {…} }
  property1: {value: "foo", writable: true, enumerable: true, configurable: true}
  property2: {value: "bar", writable: true, enumerable: true, configurable: true}
  property3: {value: 42, writable: true, enumerable: true, configurable: true}
  property4: {value: ƒ, writable: true, enumerable: true, configurable: true}
  __proto__: Object
*/
Copy after login

ES9 new features

1. async iterators

ES9 introduces asynchronous iterators ), await can be used with for...of loops to run asynchronous operations in a serial manner.

//如果在 async/await中使用循环中去调用异步函数,则不会正常执行
async function demo(arr) {
  for (let i of arr) {
    await handleDo(i);
  }
}

//ES9
async function demo(arr) {
  for await (let i of arr) {
    handleDo(i);
  }
}
Copy after login

2. Promise.finally()

A Promise call chain either successfully reaches the last .then(), or fails to trigger .catch(). In some cases, you want to run the same code regardless of whether the Promise runs successfully or fails, such as clearing, deleting the conversation, closing the database connection, etc.

.finally() allows you to specify final logic.

function doSomething() {
  doSomething1()
    .then(doSomething2)
    .then(doSomething3)
    .catch((err) => {
      console.log(err)
    })
    .finally(() => {})
}
Copy after login

3. Rest/Spread attribute

Rest: The remaining attributes of the object destructuring assignment.

Spread: Spread attribute of object destructuring assignment.

//Rest
let { fname, lname, ...rest } = { fname: "Hemanth", lname: "HM", location: "Earth", type: "Human" };
fname; //"Hemanth"
lname; //"HM"
rest; // {location: "Earth", type: "Human"}

//Spread
let info = {fname, lname, ...rest};
info; // { fname: "Hemanth", lname: "HM", location: "Earth", type: "Human" }
Copy after login

ES10 new features

1. Array’s flat() method and flatMap() method

flat( ) method will recursively traverse the array according to a specifiable depth, and merge all elements with the elements in the traversed sub-array into a new array and return it.

The flatMap() method first maps each element using a mapping function and then compresses the result into a new array. It's almost identical to map and flat with a depth value of 1, but flatMap is usually slightly more efficient when combined into one method.

let arr = ['a', 'b', ['c', 'd']];
let flattened = arr.flat();

console.log(flattened);    // => ["a", "b", "c", "d"]

arr = ['a', , , 'b', ['c', 'd']];
flattened = arr.flat();

console.log(flattened);    // => ["a", "b", "c", "d"]

arr = [10, [20, [30]]];

console.log(arr.flat());     // => [10, 20, [30]]
console.log(arr.flat(1));    // => [10, 20, [30]]
console.log(arr.flat(2));    // => [10, 20, 30]
console.log(arr.flat(Infinity));    // => [10, 20, 30]
Copy after login

2. String’s trimStart() method and trimEnd() method

分别去除字符串首尾空白字符

const str = "   string   ";

console.log(str.trimStart());    // => "string   "
console.log(str.trimEnd());      // => "   string"
Copy after login

3、Object.fromEntries()

Object.entries()方法的作用是返回一个给定对象自身可枚举属性的键值对数组,其排列与使用 for…in 循环遍历该对象时返回的顺序一致(区别在于 for-in 循环也枚举原型链中的属性)。

而 Object.fromEntries() 则是 Object.entries() 的反转,Object.fromEntries() 函数传入一个键值对的列表,并返回一个带有这些键值对的新对象。

const myArray = [['one', 1], ['two', 2], ['three', 3]];
const obj = Object.fromEntries(myArray);

console.log(obj);    // => {one: 1, two: 2, three: 3}
Copy after login

ES11新增特性

1、Promise.allSettled

Promise.all最大问题就是如果其中某个任务出现异常(reject),所有任务都会挂掉,Promise 直接进入 reject 状态。

Promise.allSettled在并发任务中,无论一个任务正常或者异常,都会返回对应的的状态(fulfilled 或者 rejected)与结果(业务 value 或者 拒因 reason),在 then 里面通过 filter 来过滤出想要的业务逻辑结果,这就能最大限度的保障业务当前状态的可访问性。

const promise1 = Promise.resolve(3);
const promise2 = new Promise((resolve, reject) => setTimeout(reject, 100, 'foo'));
const promises = [promise1, promise2];

Promise.allSettled(promises).
  then((results) => results.forEach((result) => console.log(result.status)));

// expected output:
// "fulfilled"
// "rejected"
Copy after login

2、String.prototype.matchAll

matchAll() 方法返回一个包含所有匹配正则表达式及分组捕获结果的迭代器。 在 matchAll出现之前,通过在循环中调用 regexp.exec来获取所有匹配项信息(regexp需使用 /g 标志)。如果使用 matchAll,就可以不必使用 while 循环加 exec 方式(且正则表达式需使用/g标志)。使用 matchAll会得到一个迭代器的返回值,配合 for…of, array spread, or Array.from() 可以更方便实现功能。

const regexp = /t(e)(st(\d?))/g;
const str = 'test1test2';

const array = [...str.matchAll(regexp)];

console.log(array[0]);
// expected output: Array ["test1", "e", "st1", "1"]

console.log(array[1]);
// expected output: Array ["test2", "e", "st2", "2"]
Copy after login

ES12新增特性

1、Promise.any

Promise.any() 接收一个Promise可迭代对象,只要其中的一个 promise 成功,就返回那个已经成功的 promise 。如果可迭代对象中没有一个 promise 成功(即所有的 promises 都失败/拒绝),就返回一个失败的 promise。

const promise1 = new Promise((resolve, reject) => reject('我是失败的Promise_1'));
const promise2 = new Promise((resolve, reject) => reject('我是失败的Promise_2'));
const promiseList = [promise1, promise2];
Promise.any(promiseList)
.then(values=>{
  console.log(values);
})
.catch(e=>{
  console.log(e);
});
Copy after login

2、逻辑运算符和赋值表达式

逻辑运算符和赋值表达式,新特性结合了逻辑运算符(&&=,||=,??=)。

a ||= b
//等价于
a = a || (a = b)

a &&= b
//等价于
a = a && (a = b)

a ??= b
//等价于
a = a ?? (a = b)
Copy after login

3、replaceAll

返回一个全新的字符串,所有符合匹配规则的字符都将被替换掉。

const str = 'hello world';
str.replaceAll('l', ''); // "heo word"
Copy after login

4、数字分隔符

数字分隔符,可以在数字之间创建可视化分隔符,通过_下划线来分割数字,使数字更具可读性。

const money = 1_000_000_000;
//等价于
const money = 1000000000;

1_000_000_000 === 1000000000; // true
Copy after login

【相关推荐:javascript学习教程

The above is the detailed content of What features does ecmascript have?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!