1, Es5 and ES6 differences, say what you know about ES6

ECMAScript5, or ES5, is the fifth revision of ECMAScript and was standardized in 2009

ECMAScript6, also known as ES2015, is the sixth revision of ECMAScript, completed in 2015

ES6 is an improvement over ES5. Compared with ES5, it is simpler and improves development efficiency

Some new ES6 features:

Let declares variables and const declares constants, both of which have block-level scope

There is no block-level scope in ES5, and var has variable promotion. In LET, variables used must be declared

Arrow function

Function definitions in ES6 no longer use the keyword function(), but are defined with ()=> instead

This always points to the function closest to this when the arrow function is defined. If there is no function closest to this, it points to window.

Template string

Template strings are enhanced strings, identified by backquotes (‘), that can be used either as regular strings or to define multi-line strings

Var name = 'c '; Var desc = 'Lilac Doctor is a popular sexual health website '; Var HTML = function(name, desc){var TPL = 'name '+' n'+ '+ '; return tpl; ${name} ${desc} ';Copy the code

 

Deconstruction assignment

ES6 allows you to extract values from arrays and objects and assign values to variables in a pattern

The for of circulation

for… The of loop can iterate over groups of numbers, Set and Map structures, some array-like objects, objects, and strings

Application scenarios

// Arguments is an array-like object, usually you need to convert it to an array before iterating, but for... Function sum() {let sum = 0 for(let num of arguments){sum += num} console.log(sum); / / 15} sum (1, 2, 3, 4, 5) / / traversal string name = 'Asher'; for (let char of name){ console.log(char); <style type="text/ CSS ">. Completed {text-decoration: line-through; } </style> <body> <ul> <li>yoga</li> <li>boxing</li> <li>press</li> </ul> <script type="text/javascript"> const lis = document.querySelectorAll('li'); for(let li of lis){ li.addEventListener('click',function(){ this.classList.toggle('completed'); }) } </script> </body>Copy the code

Import and export Import and export

ES6 standard, Js native support module (module). The JS code is divided into small blocks of different functions for modularization, the code of different functions are written in different files, each module only needs to export the public interface part, and then through the import of the module can be used in other places

Set data structure

Set data structure, similar to an array. All data are unique and have no duplicate values. It is itself a constructor

application

Let arr = [3, 5, 2, 2, 5, 5]; let unique = [...new Set(arr)]; // [3, 5, 2] let a = new Set([1, 2, 3]); let b = new Set([4, 3, 2]); // let union = new Set([...a,...b]); / / the Set {1, 2, 3, 4} / / intersection let intersects = new Set ([...] a filter (x = > b.h as (x))); // set {2, 3} // let difference = new set ([...a]. Filter (x =>! b.has(x))); // Set {1}Copy the code

. Expansion operator

You can expand values in arrays or objects; You can also collect multiple values into a single variable

application

1. Merge array arr1.push(... Arr2) // Append arr2 to the end of the array arr1.unshift(... Var arr = [1,2,3]; var arr2 = [...arr]; // Similar to arr.slice() arr2.push(4) // Remember: objects in arrays are still reference values, so nothing is "copied" over. Array var myFn = function(... args) { // ... } let numbers = [9, 4, 7, 1]; Math.min(... numbers); Math.min. Apply (numbers);Copy the code

Decorator @

A decorator is a function that modifies the behavior of a class or even a method. Modifiers are essentially functions that are executed at compile time

Class class inheritance

Instead of using prototype chains for inheritance as in ES5, ES6 introduces the concept of Class

class Person { constructor(name, age) { this.name = name; this.age = age; } sayName(){ console.log("the name is:"+this.name); } } class Worker extends Person{ constructor(name, age,job) { super(name, age); this.job = job; } sayJob(){ console.log("the job is:"+this.job) } } var worker = new Worker('tcy',20,'teacher'); worker.sayJob(); //the job is:teacher worker.sayName(); //the name is:tcyCopy the code

Async and await

With async/await, along with promise, you can improve code simplicity and readability by writing code that looks like synchronization to handle asynchronous processes

Async is used to declare that a function is asynchronous and await is used to wait for an asynchronous method to complete

Function doubleAfter2seconds(num) {return new Promise(resolve, resolve) reject) => { setTimeout(() => { resolve(2 * num) }, 2000); }) } async function testResult () { let first = await doubleAfter2seconds(10); let second = await doubleAfter2seconds(20); console.log(first + second); }Copy the code

promise

Promise is a solution to asynchronous programming that is more reasonable and powerful than traditional solutions (callback functions and events)

New Promise((resolve,reject)=>{if(' success ') resolve(1); If (' reject ') reject(0); }). Then (()=>{console.log(" success "); }). Catch (()=>{console.log(" failed "); })Copy the code

It is in three states: pending, resolved, and rejected.

The Promise constructor contains one parameter and a callback with resolve and reject parameters. Perform some operation (asynchronous, for example) in the callback, calling resolve if all is well, reject otherwise. You can call the promise.then() method on an already instantiated Promise object, passing the resolve and reject methods as callbacks. The then() method takes two arguments, onResolve and onReject, which represent the current Promise object when it succeeds or fails.

var promise = new Promise((resolve, reject) => { var success = true; If (success) {resolve(' success '); } else {reject(' reject '); } }).then( (data) => { console.log(data)}, (err) => { console.log(err)} )Copy the code

The implementation of a promise

setTimeout(function() { console.log(0); }, 0); var promise = new Promise((resolve, reject) => { console.log(1); setTimeout(function () { var success = true; If (success) {resolve(' success '); } else {reject(' reject '); }}, 2000); }).then( (data) => { console.log(data)}, (data) => { console.log(data)} ); console.log(promise); //<pending> Pending setTimeout(function () {console.log(promise); //<resolved> accomplished},2500); console.log(2); //1 //Promise {<resolved>: undefined}Copy the code

Symbol

Symbol is a basic type. The Symbol is generated by calling the Symbol function, which accepts an optional name argument. The Symbol returned by the function is unique

let s1 = Symbol() let s2 = Symbol('another symbol') let s3 = Symbol('another symbol') s1 === s2 // false s2 === s3 // False //symbol is uniqueCopy the code

Application Scenario 1: Use Symbol as object attribute name (key)

Before this, we used to define or access attributes of objects using strings, such as the following code: let obj = {ABC: 123, "hello": "World"} obj[" ABC "] // 123 obj["hello"] // 'world' now, Symbol can also be used to define and access object attributes:  const PROP_NAME = Symbol() const PROP_AGE = Symbol() let obj = { [PROP_NAME]: } obj[PROP_AGE] = 18 obj[PROP_NAME] // 18 then comes another very noteworthy problem: When we use Symbol as the attribute key of the object, how will the enumeration of the key be different? In practice, we often need to use object.keys () or for... In enumerates object property names. How does a Symbol key behave differently in this respect? Let obj = {[Symbol('name')]: '1 ', age: 18, title: 'Engineer'} object.keys (obj) // ['age', 'title'] for (let p in obj) {console.log(p) 'age' and 'title'} Object. GetOwnPropertyNames (obj) / / [' age ', 'title'] by the code, the Symbol type of key is not through the Object. The keys () or for... In, which is not included in the property names of the object itself. So, using this feature, we can use Symbol to define some properties that do not require external manipulation and access. Because of this feature, when converting objects to JSON strings using json.stringify (), the Symbol attribute is also excluded from the output: Json.stringify (obj) // {"age":18,"title":"Engineer"} we can use this feature to better design our data objects, making "internal manipulation" and "external selective output" more elegant. However, in this case, we can not obtain the object properties defined in Symbol mode? No. There will still be apis specific to Symbol, such as: / / the use of Object API Object. GetOwnPropertySymbols (obj) / / [Symbol (name)] / / use the new reflection API Reflect. OwnKeys (obj) / / [Symbol(name), 'age', 'title']Copy the code

Application Scenario 2: Use symbols instead of constants

Take a look at the following code. Is it common in your code? const TYPE_AUDIO = 'AUDIO' const TYPE_VIDEO = 'VIDEO' const TYPE_IMAGE = 'IMAGE' function handleFileResource(resource) {  switch(resource.type) { case TYPE_AUDIO: playAudio(resource) break case TYPE_VIDEO: playVideo(resource) break case TYPE_IMAGE: previewImage(resource) break default: Throw new Error('Unknown type of resource')}} Throw new Error('Unknown type of resource')}} As in the code above, we often define a set of constants to represent several different types of a business logic. We usually want these constants to be unique to each other. To ensure this, We need to assign unique values to constants ('AUDIO', 'VIDEO', 'IMAGE' here). Small constants are fine, but with more constants, you might need to be more careful about giving them better names. Now with Symbol, we don't have to go to so much trouble. Const TYPE_AUDIO = Symbol() const TYPE_VIDEO = Symbol() const TYPE_IMAGE = Symbol() const TYPE_AUDIO = Symbol() Isn't that convenient?Copy the code

Application Scenario 3: Use Symbol to define private attributes/methods of a class

We know that in JavaScript, there is no access control keyword private in object-oriented languages such as Java, where all properties or methods defined on a class are publicly accessible. So this caused a little bit of confusion when we were designing the API. Symbol and the modularity mechanism make private properties and methods of classes possible. Such as: Const PASSWORD = Symbol() class Login {constructor(username, constructor) password) { this.username = username this[PASSWORD] = password } checkPassword(pwd) { return this[PASSWORD] === pwd } } Import Login from './a' const Login = new Login('admin', '123456') login.checkPassword('123456') // true login.PASSWORD // oh! no! login[PASSWORD] // oh! no! login["PASSWORD"] // oh! no! Because the Symbol constant PASSWORD is defined in the module where A. Js is located, the outside module cannot obtain this Symbol, and it is impossible to create an identical Symbol (because Symbol is unique). Therefore, the Symbol of this PASSWORD can only be used within A. js, so the class attributes defined by it cannot be accessed outside the module, achieving a privatized effect.Copy the code

The Proxy agent

You use a Proxy to listen for an object and then do something about it

ES6 natively provides a Proxy constructor to generate a Proxy instance. var proxy = new Proxy(target, handler); All uses of Proxy objects are in this form. The only difference is how the Handle parameter is written. New Proxy is used to generate the Proxy instance, target represents the object to be intercepted, and Handle is used to customize the interception behavior. var proxy = new Proxy({}, { get: function(target, property) { return 35; }}); Proxy. time // 35 proxy.name // 35 proxy.title // 35 For the Proxy to work, you must operate on the Proxy instance, not the target object.Copy the code

Var, let, const

  • Var declarations can be repeated, while let declarations cannot be repeated
  • Var is not limited to the block level, while LET is limited to the block level
  • Var maps to Window (hanging an attribute), while let does not map to Window
  • Var can access a variable above a declaration, while let has a temporary dead band. Accessing a variable above a declaration will result in an error
  • Const must be assigned after the declaration or an error will be reported
  • Const defines an immutable quantity, and an error is reported if it changes
  • Const, like let, does not map to window, supports block-level scope, and raises an error when accessing a variable above a declaration

3. What should I pay attention to when using arrow functions?

  • With the arrow function, this does not point to the window, but to the parent (which is mutable). When we use => to define a function, this points to the object at which we defined it, not the object at which we used it
  • Arguments objects cannot be used
  • Cannot be used as a constructor, which means that the new command cannot be used, otherwise an error will be thrown
  • Yield cannot be used, so arrow functions cannot be used as Generator functions

The direction of this is always confusing, but with => mom doesn’t have to worry about you using this anymore

class Animal { constructor(){ this.type = 'animal' } says(say) { setTimeout(function () { console.log(this.type + 'says' + say)},1000)}} var animal = new animal () animal. Says ('hi') // undefined constructor() { this.type = 'animal' } says(say) { setTimeout(() => { console.log(this.type + ' says ' + say) }, 1000) } } var animal = new Animal() animal.says('hi') // animal says hiCopy the code

What are the new features of template strings in ES6? And implement a class template string function

Basic string formatting. Concatenate an expression into a string. Delimit with ${}

In ES5 we use a backslash () to do multi-line strings or string concatenation. ES6 backquotes (‘ ‘) do this

let name = 'web'; let age = 10; Let STR = 'hello ${name} is ${age} years old' STR = STR. Replace (/ $\ \ {\} ([^}] *)/g, function () {return eval (the arguments [1]). }) console.log(str); // Hello, Web is 10 years oldCopy the code

5, introduce the difference between Set and Map.

Application Scenario Set is used for data reorganization, and Map is used for data storage

Set

  • Members cannot be duplicated
  • There are only key values without key names, just like an array
  • You can iterate through it with methods like add, delete,has

Map

  • It’s essentially a set of key pairs, sort of a set
  • You can traverse, you can convert to any data format

6. ECMAScript 6 says “class”

ES6 class is a syntactic candy that does most of what ES5 does. The new class writing method just makes object prototype writing clearer and more like object-oriented programming syntax

Class Point{constructor(x,y){this.x = x; //this keyword represents the instance object this.y = y; } toString(){ return `(${this.x},${this.y})`; // On the Windows keyboard, ' 'is the key above the English input method TAB key. //'('+this.x+','+this.y+')'; }} let p =new Point(1,2); p.toString(); / / "(1, 2)"Copy the code

  

7. Is the Promise constructor executed synchronously or asynchronously, but what about the then method?

The Promise constructor is executed synchronously, and the THEN method asynchronously

8, setTimeout, Promise, Async/Await difference

The event loop is divided into macro task queue and micro task queue

The setTimeout callback is placed in the macro task queue until the execution stack is empty

The callback function in promise.then will be placed in the microtask queue of the corresponding macro task until the synchronous code in the macro task completes execution

Async means that there may be an asynchronous method inside the function, await followed by an expression

When an async method executes, an await expression is immediately executed and the code following the expression is placed on the microtask queue, freeing the execution stack for the synchronous code to execute first

9. Promise has several states. When does it enter a catch?

There are three states: pending, depressing and reject

There are two processes: pending -> depressing, pending -> Rejected

When pending is Rejected, a catch is entered

10. What is the output below

const promise = new Promise((resolve, reject) => {
    console.log(1);
    resolve();
    console.log(2);
})

promise.then(() => {
    console.log(3);
})

console.log(4);

// 1 2 4 3
Copy the code

A Promise executes immediately after it is created, so it prints 1,2 first, while the code inside promise.then () executes immediately at the end of the next event loop, so it continues to print 4, and finally prints 3.

Design an object whose key name contains at least one symbol type and iterate over all keys

let name = Symbol('name'); Let product = {[name]:" ", "price":799}; Reflect.ownKeys(product); / / Reflect. OwnKeys () : the equivalent of the Object. GetOwnPropertyNames (target) concat (Object. GetOwnPropertySymbols (target)Copy the code

12, the following Set structure, print the size value is what

let s = new Set(); s.add([1]); s.add([1]); console.log(s.size); / / 2Copy the code

The two arrays [1] do not have the same value. The arrays they define correspond to different storage addresses in memory, so they do not have the same value

Can be stored in a Set structure, so size is 2

13. What is the difference between a reject and a catch in Promise

  • Reject is used to throw exceptions and catch is used to handle exceptions
  • Reject is a method for a Promise, and catch is a method for an instance of a Promise
  • Anything after reject must go into the second callback in THEN, or catch if no second callback is written in THEN
  • Network exceptions (such as disconnection) go directly to catch and not to the second callback of THEN

Write a promise using class

Class Promise{constructor(executer){constructor(){this.status = 'pending'; Value = undefined// Default value for success undefined this.reason = undefined// Default value for failure undefined// State can only be changed pending If (this.status == pending){this.status = 'resolve'; this.value = value; Let rejectFn = reason =>{if(this.status == pending){this.status = 'reject'; this.reason = reason; } // pass resolve and reject to executer executer(resolve,reject); }catch(e){ reject(e); OnFufilled if(this.status = 'resolve'){onFufilled(this.value); } // Call onReject if(this.status = 'reject'){onReject(this.reason); }}}Copy the code

15, How to use Set to remove weights

Let arr =,43,23,43,68,12 [12]; let item = [...new Set(arr)]; console.log(item); //[12, 43, 23, 68] let item1 = Array.from(new Set(arr)); console.log(item1); / / [12, 43, 23, 68]Copy the code

16. Change the form for loop below to for of

Let arr =,22,33,44,55 [11]; let sum = 0; for(let i=0; i<arr.length; i++){ sum += arr[i]; }Copy the code

The answer:

Let arr =,22,33,44,55 [11]; let sum = 0; for(value of arr){ sum += value; }Copy the code

Count the numbers :for in and for of

for(let i in arr ){
    console.log(arr[i])
}
for(let i of arr){
    console.log(i);
}
Copy the code

Understand async/await and its advantages over Generator

  • Async await is used to address async, async functions are syntactic sugar for Generator functions
  • Async is represented with the keyword async and await is used inside the function
  • The async function returns a Promise object, and callbacks can be added using the then method
  • When a function executes, it returns as soon as it encounters await, waits for the asynchronous operation to complete, and then executes the following statement in the function body

Advantages of Async over Generator:

  • Built-in actuators. The execution of Generator functions must depend on the executor, whereas Aysnc functions have their own executor and are called in the same way as normal functions
  • Better semantics. Async and await are more semantic than * and yield
  • Wider applicability. The yield command can only be followed by a Thunk function or a Promise object, and the async function can be followed by a Promise or a primitive value
  • The return value is Promise. Async functions return Promise objects, which are more convenient than iterators returned by Generator functions and can be called directly using then()

18. ForEach, for in, for of

  • ForEach is more used to iterate over groups of numbers

  • For in is usually used to iterate over objects or JSON

  • Keys () and object.keys ().

  • For in loops for key, for of loops for value

    Var user = {name:’ x ‘,age:10,sex:’ x ‘} for(let index in user){console.log(index+’:’+user[index]) } for(let index of object.keys (user)){console.log(index+’:’+user[index]) {console.log(index+’:’+user[index]) //”name: zhang SAN “”age:10″”sex: male “}

19. Talk about the import/export module of ES6

Import through the import keyword

// Import only one import {sum} from "./example.js" // Import multiple import {sum,multiply,time} from "./exportExample.js" // Import a whole module import  * as example from "./exportExample.js"Copy the code

Export using the export keyword

Var firstName = 'Michael'; var firstName = 'Michael'; export var lastName = 'Jackson'; export var year = 1958; Var firstName = 'Michael'; var firstName = 'Michael'; var lastName = 'Jackson'; var year = 1958; export {firstName, lastName, year}; Let bosh = function CRS (){} export default bosh; import crc from 'crc'; // If export default is not used, the corresponding import statement needs braces. Let bosh = function CRS (){} export bosh; import {crc} from 'crc';Copy the code