In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the relevant knowledge of "what are the characteristics of ecmascript". In the operation of actual cases, many people will encounter such a dilemma. Then let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
The characteristics of ecmascript are: 1, class (class); 2, modularization; 3, arrow function; 4, template string; 5, deconstructing assignment; 6, extension operator; 7, Promise;8, let and const;9, exponential operator "*"; 10, "async/await" and so on.
The operating environment of this tutorial: windows7 system, javascript1.8.5 version, Dell G3 computer.
What is ECMAScript?
ECMAScript is a script programming language standardized by ECMA International (formerly known as the European Association of computer Manufacturers) through ECMA-262.
Ecma International (Ecma International) is an international information and telecommunications standards organization for membership. Before 1994, it was called the European Association of computer Manufacturers (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.
Unlike national government standards bodies, Ecma International is an enterprise membership organization. The organization's standardization process is more commercial, claiming that this mode of operation reduces the bureaucratic pursuit of effectiveness.
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, ECMAScript specification, C # language specification, C++/CLI language specification and so on.
The relationship between ECMAScript and JavaScript
In November 1996, Netscape, the creator of JavaScript, decided to submit JavaScript to the standardization organization ECMA, hoping that the language would become an international standard. The following year, ECMA released the first version of Standard document 262 (ECMA-262), which defined the standard for the browser scripting language and called it ECMAScript, version 1.0.
The standard was developed for the JavaScript language from the beginning, but it is not called JavaScript for two reasons. One is the trademark, Java is the 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, the maker of the language is ECMA, not Netscape, which helps to ensure the openness and neutrality of the language.
Therefore, the relationship between ECMAScript and JavaScript is that the former is the 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 common. What is the relationship between it and ES6?
After the release of ECMAScript version 5.1 in 2011, version 6.0 began to be developed. 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 functions, and during the development process, many organizations and individuals continue to submit new features. It soon became clear that it was impossible to include all the features to be introduced in one version. The general practice is to release version 6.0 first, then release version 6.1 after a period of time, then version 6.2, version 6.3, and so on.
The Standards Committee finally decided that the standard would be officially released in June of each year as the official version of that year. In the following time, changes will be made on the basis of this version, and the draft will naturally become the new year's version until June of the next year. In this way, you don't need the previous version number, just use the year mark.
Therefore, ES6 is not only a historical term, but also a general reference, meaning the next generation standard of JavaScript after version 5.1, covering ES2015, ES2016, ES2017 and so on, while ES2015 is the official name, especially the language standard of the official version released in that year.
History of ECMAScript
In November 1996, Netscape submitted Js to the international standards organization ECMA, which was able to become an international standard.
In 1997, ECMAScript version 1.0 was launched. (this year, ECMA released the first version of Standard document No. 262 (ECMA-262), which sets the standard for the browser scripting language and calls it ECMAScript, the ES1.0 version. )
In June 1998, ES version 2.0 was released.
In December 1999, ES 3.0 was released and became the general standard of JS and was widely supported.
In October 2007, the draft version 4.0 of ES was released.
In July 2008, due to the great differences between the parties, ECMA decided to terminate the development of ES 4.0. Instead, a small portion of it related to existing functional improvements is released as ES 3.1. But it changed its name to ES version 5.0shortly after the reply.
In December 2009, ES version 5.0 was officially released.
In June 2011, ES version 5.1 was released and became the ISO international standard (ISO/IEC 16262 ISO/IEC 2011).
In March 2013, the ES 6 draft ended and no new features were added.
In December 2013, draft ES 6 was released.
The official version of ES 6 was released in June 2015.
Since then, an official version has been released every June, so the latest version is ES12, which is released in June 2021.
New features in each version of ECMAScript ES6 new features
1 、 class
ES6 introduces class (classes) to make object-oriented programming in JavaScript easier and easier to understand.
Class Student {constructor () {console.log ("I'm a student.");} study () {console.log ('studyboy');} static read () {console.log ("Reading Now.");}} console.log (typeof Student); / / functionlet stu = new Student (); / / "I'm a student." stu.study (); / / "study!" stu.read (); / / "Reading Now."
2. Modularization
ES5 supports native modularity, and modules are added as an important part of ES6. The function of the module is mainly composed of export and import. Each module has its own scope, the mutual calling relationship between modules is to specify the interface exposed by the module through export, and to refer to the interface provided by other modules through import. At the same time, it also creates a namespace for the module to prevent function naming conflicts.
Export function sum (x, y) {return x + y;} export var pi = 3.141593 position 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)
3. Arrow function
= > is not just an abbreviation for the keyword function, it also brings other benefits. The arrow function shares the same this with the code that surrounds it, which can help you solve the problem of pointing to this. For example, patterns such as var self = this; or var that = this refer to the peripheral this. But with the help of = >, this mode is not needed.
() = > 1v = > return 1 (AMagneb) = > aquib () = > {alert ("foo");} e = > {if (e = = 0) {return 0;} return 1000game;}
4. Template string
ES6 supports template strings, which makes the stitching of strings more concise and intuitive.
/ / do not use the template string var name = 'Your name is' + first +''+ last +'. / / use the template string var name = `template ${first} ${last}. `
The string can be concatenated with ${} in ES6, just put the variable in curly braces.
5. Deconstruction assignment
Deconstructing assignment syntax is an expression of JavaScript, which can easily extract values from arrays or objects to assign values to defined variables.
/ / object const student = {name: 'Sam', age: 22, sex:' male'} / array / / const student = ['Sam', 22,' male']; / / ES5 Const name = student.name;const age = student.age;const sex = student.sex;console.log (name +'-'+ age +'-'+ sex); / / ES6const {name, age, sex} = student;console.log (name +'-'+ age +'- -'+ sex)
6. Extend operator
Extend operator... Array expressions or string can be expanded at the syntax level when function calls / array constructions are made, and object expressions can be expanded as key-value when constructing objects.
/ / use the extension operator function sum (x, y, z) {return x + y + z} const numbers = [1,2,3] console.log (sum (.. calls)) / / array const stuendts = ['Jine',' Tom'] const persons = ['Tony',... stuendts,' Aaron', 'Anna'] conslog.log (persions) when the function is called
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, and ES6 wrote it into the language standard, unified usage, and natively provided Promise objects.
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', error);})
8. Let and const
Previously, JS has no block-level scope, const and let fill this convenient gap, const and let are both block-level scope.
Function f () {{let x; {/ / correct const x = "sneaky"; / / error, constant const x = "foo";} / / error, declared variable let x = "inner";}} new features for ES7
1. Array.prototype.includes ()
The includes () function determines whether an array contains a specified value, returns true if it does, and returns false otherwise.
[1, 2, 3] .false (- 1) / / false [1, 2, 3] .cow (1) / / true [1, 2, 3] .cow (3, 4) / / false [1, 2, 3] .sister (3, 3) / / false [1, 2, NaN] .sister (NaN) / / true ['foo'] 'bar',' quux'] .clients ('foo') / / true [' foo', 'bar',' quux'] .clients ('norf') / / false
2. Exponential operator
The exponential operator * * is introduced in ES7, which has the same as Math.pow (…) The equivalent calculation result. Use the exponential operator * *, just like the +, -, and so on.
/ / previous versions of Math.pow (5,2) / / ES75 * * 2max / 5 * * 2 = 5 * 5ES8 new features
1 、 async/await
The asynchronous function returns an AsyncFunction object and loops the asynchronous operation through the event.
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 ()
2. Object.values ()
Object.values () is a new function similar to Object.keys (), but returns all the values of Object's own properties, excluding inherited values.
Const obj = {a: 1, b: 2, c: 3} / / do not use Object.values () const vals = Object.keys (obj). Map ((key) = > obj [key]) console.log (vals) / / use Object.values () const values = Object.values (obj1) console.log (values)
You can see from the above code that Object.values () saves us the step of traversing the key and getting the value based on these key.
3. Object.entries ()
The Object.entries () function returns an array of key-value pairs for enumerable properties of a given object itself.
/ / do not use Object.entries () Object.keys (obj). ForEach ((key) = > {console.log ('key:' + key +' value:' + obj [key])}) / / key:b value:2// use Object.entries () for (let [key, value] of Object.entries (obj1)) {console.log (`key: ${key} value:$ {value} `)} / / key:b value:2
4 、 String padding
Two new instance functions String.prototype.padStart and String.prototype.padEnd have been added to String in ES8, allowing empty strings or other strings to be 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'))
5. Object.getOwnPropertyDescriptors ()
The Object.getOwnPropertyDescriptors () function is used to get descriptors for all its own properties of an object, and returns an empty object if it does not have any of its own properties.
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: proto__: Object*/ES9, writable: true, enumerable: true, configurable: true} _ proto__: Object*/ES9
1 、 async iterators
ES9 introduces an asynchronous iterator (asynchronous iterators), and await can work with for. Of loops are used together to run asynchronous operations in a serial manner.
/ / if an asynchronous function is called in a loop in async/await, async function demo (arr) {for (let i of arr) {await handleDo (I);}} / / ES9async function demo (arr) {for await (let i of arr) {handleDo (I);}} will not be executed normally.
2. Promise.finally ()
A chain of Promise calls either succeeds in reaching 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 not, such as clearing, deleting dialogs, closing database connections, etc.
Finally () allows you to specify the final logic.
Function doSomething () {doSomething1 () .then (doSomething2) .then (doSomething3) .catch ((err) = > {console.log (err)}) .finally (() = > {})}
3. Rest/Spread attribute
Rest: the object deconstructs the remaining properties of the assignment.
Spread: object deconstructs the propagation property of the assignment.
/ Restlet {fname, lname,... rest} = {fname: "Hemanth", lname: "HM", location: "Earth", type: "Human"}; fname; / / "Hemanth" lname; / / "HM" rest; / / {location: "Earth", type: "Human"} / / Spreadlet info = {fname, lname,... rest}; info / / {fname: "Hemanth", lname: "HM", location: "Earth", type: "Human"} ES10 new features
1. Flat () method and flatMap () method of Array.
The flat () method recursively traverses the array at a specified depth and merges all elements with the elements in the traversed subarray into a new array.
The flatMap () method first maps each element using a mapping function, and then compresses the result into a new array. It is almost the same as map and flat with a depth value of 1, but flatMap is usually slightly more efficient in merging into one method.
Let arr = ['averse,' baked, ['clocked,' d']]; let flattened = arr.flat (); console.log (flattened); / / = > ["a", "b", "c", "d"] arr = ['a', 'baked, [' cased,'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]
2. TrimStart () method and trimEnd () method of String.
Remove the white space characters at the beginning and the end of the string respectively
Const str = "string"; console.log (str.trimStart ()); / / = > "string" console.log (str.trimEnd ()); / / = > "string"
3. Object.fromEntries ()
The function of the Object.entries () method is to return an array of key-value pairs of enumerable properties of a given object, which arranges and uses for. The in loop returns in the same order as it iterates through the object (the difference is that the for-in loop also enumerates properties in the prototype chain).
Object.fromEntries () is the reverse of Object.entries (), and the Object.fromEntries () function passes in a list of key-value pairs and returns a new object with these key-value pairs.
Const myArray = [['one', 1], [' two', 2], ['three', 3]]; const obj = Object.fromEntries (myArray); console.log (obj); / / = > {one: 1, two: 2, three: 3} New features for ES11
1 、 Promise.allSettled
The biggest problem with Promise.all is that if one of the tasks has an exception (reject), all tasks will die and the Promise will directly enter the reject state.
In concurrent tasks, Promise.allSettled returns the corresponding status (fulfilled or rejected) and result (business value or reason) regardless of whether a task is normal or abnormal. In then, the desired business logic results are filtered through filter, which can maximize the accessibility of the current state of the business.
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"
2 、 String.prototype.matchAll
The matchAll () method returns an iterator that contains all matching regular expressions and packet capture results. Before matchAll appeared, all matches were obtained by calling regexp.exec in the loop (regexp needs to use the / g flag). If you use matchAll, you don't have to use the while loop plus exec (and regular expressions use the / g flag). Using matchAll will get the return value of an iterator, together with for. Of, array spread, or Array.from () can be more convenient to implement the function.
Const regexp = / t (e) (st (\ d?)) / GTX 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"] ES12 new features
1 、 Promise.any
Promise.any () receives an Promise iterable object and returns the promise that has succeeded as long as one of the promise succeeds. If none of the promise in the iterable object succeeds (that is, all promises fail / reject), a failed promise is returned.
Const promise1 = new Promise ((resolve, reject) = > reject ('I am the failed Promise_1'); const promise2 = new Promise ((resolve, reject) = > reject ('I am the failed Promise_2')); const promiseList = [promise1, promise2]; Promise.any (promiseList) .then (values= > {console.log (values);}) .catch (e = > {console.log (e);})
2. Logical operators and assignment expressions
Logical operators and assignment expressions, the new features combine the logical operators (& & =, | =,? =).
A | | = bstroke / equivalent to a = a | (a = b) a & & = bhand / equivalent to a = a & & (a = b) a? (a = b)
3 、 replaceAll
Returns a brand new string, and all characters that match the matching rules will be replaced.
Const str = 'hello world';str.replaceAll (' lumped,'); / / "heo word"
4. Numeric separator
A numeric separator that creates a visual separator between numbers and splits them with an underscore to make them more readable.
Const money = 1000000 characters / equivalent to const money = 10000000position 10000000000 = = 10000000000; / / true, what are the characteristics of ecmascript? thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.