Ajax

1. What is the principle of Ajax

  • Implementation principle:
    • At its heart is the XMLHttpRequest object
    • Internet Explorer uses ActiveXObject
  • Common attributes:
    • The onreadystatechange property
      • The function that holds the server response
xhr.onreadystatechange=function(){
    // We can do something here
}
Copy the code
  • ReadyState attribute
    • Stores the status information of the server response. The onReadyStatechange function is executed whenever readyState changes, and the readyState property may have values
    • Add a judgment statement to the onreadyStatechange function to test whether the response was successful
xhr.onreadystatechange=function(){
      // We can do something here
      if(xhr.readyState===4) {// Get the data from the service's response}}Copy the code
  • responseText
    • You can get the data returned by the server via the responseText property
xhr.onreadystatechange=function(){
    // We can do something here
    if(xhr.readyState===4) {// Get the data from the service's response
        document.myForm.time.value= xhr.reponseText
    }
}
Copy the code
  • Other attributes

  • Common methods:
    • Open () method
      • Open () takes three arguments,The first parameter defines the method used to send the requestSecond parameterSpecify the URL of the server-side script,, the third parameterSpecifies that the current request should be processed asynchronously
xhr.opne('GET',test.php,true) // true represents asynchrony
Copy the code
  • The send () method
    • The send() method sends the request to the server, assuming the HTML file is in the same directory as the PHP file, and the code looks like this
xhr.send(null)
Copy the code
  • Other methods
  • Send an Ajax-get request
    • Create an XMLHttpRequest object
    • Setting the request Mode
    • Call the callback function
    • Send the request
// 1- Create an object
let xhr =new  XMLHttpRequest()
var url = `http://location:8080/ajaxGet/login`
// 2- Sets request parameters
xhr.opne('GET',url,true)
// 3- Send the request
xhr.send()
// 4- Register events
xhr.onreadystatechange=function(){
    if(xhr.readyState===4 && xhr.status===200) {var obj = document.getElementById('id')
            obj.innerHTML= xml.responseText 
    } else{
            alert('Ajax server returns error')}}Copy the code
  • Send an Ajax-POST request
    • To send a POST request, add a request header; otherwise, an error message will be displayed
// 1- Create an object
let xhr =new  XMLHttpRequest()
var url = `http://location:8080/ajaxGet/login`
//2 -post requests must include a request header otherwise an error will be reported
xhr.setRequestHeader("Content-type"."application/x-www-form-urlencoded");
// 3- Sets request parameters
xhr.open('PSOT',url,true)
// 4- Send the request
xhr.send()
// 5- Register event
xhr.onreadystatechange=function(){
    if(xhr.readyState===4 && xhr.status === 200) {// The response succeeded. What do I do
            var obj = document.getElementById('id')
            obj.innerHTML= xml.responseText 
    }  else{
            alert('Ajax server returns error')}}Copy the code

2. What are the differences between Get and POST requests

  • use
    • Get is often used to get, and POST is used to submit data
  • security
    • Get than postA relatively safe
    • Get directly exposes parameters in the Url address bar, and POST directly exposes parameters in the request body. The browser will cache the PARAMETERS. If the password and user name are cached, it will cause leakage, resulting in insecurity
  • Request parameters
    • The queryString is part of the URL, you can take get and POST,get’s QueryString (urlencode only), and the POST parameter is put in the Body.
  • Request parameter length limits
    • The maximum length of a get request is 1024kb, and the maximum length of a post request is unlimited
    • In the HTTP specification, there is no size limit for GET requests, but browsers have limits on URL length, which are theoretically unlimited for Post
  • TCP packet
    • A GET request generates one TCP packet, and a POST request generates two TCP packets

Explain JavaScript’s same-origin policy

  • meaning
    • The same origin policy means that the following three must be unified. If one is different, cross-domain will occur
      • The domain name
      • agreement
      • port
  • purpose
    • In order to ensure user information security and prevent malicious websites from stealing data, the same-origin policy assumes that A user logs in to website A and then browses other websites, but website B can obtain the cookies of website A, and then user information will be leaked
  • limit
    • Cookie,LocalStorage, and indexDB cannot be obtained
    • DOM not available
    • Ajax requests cannot be sent
  • To evade restrictions
    • cookie
      • Cookie is a piece of information written by the server into the browser. Only web pages with the same origin can share cookies. However, the first-level domain names of two web pages are the same, but the second-level domain names are differentdocument.domainSharing Cookie Information
      • Two pages with different sources: unable to get each other’s DOM, useIframeandwindow.opneMethod to open a window
    • LocalStorage
      • The postMessage() method allows cross-window communication, regardless of whether the two are homologous or not. The method has two parameters: the specific information content of parameter 1 and the source (protocol + domain + port) of the receiving window of parameter 2 can also be set to * to indicate that the message is sent to all Windows without restriction
    • ajax
      • jsonp
      • cors

4. What are the ways to solve cross-domain problems

  • jsonp
    • The basic definition
      • By adding a script element, the server requests JSON data, regardless of the same origin policy, using the SRC attribute in the script. When the server receives the request, it passes the data back to a named callback function
    • The specific implementation
var script = document.createElement('script');
script.setAttribute("type"."text/javascript");
script.src = src;
document.body.appendChild(script);
}
window.onload = function () {
  addScriptTag('http://example.com/ip?callback=foo');
}

function foo(data) {
  console.log('Your public IP address is: ' + data.ip);
    
 //=============________ server-side code
// When the server receives the request, it puts the data in the parameter position of the function
foo({
  "ip": "8.8.8.8"
});
Copy the code
  • disadvantages
    • Only Get requests can be sent, but Post requests cannot be processed
    • It only supports clearing of HTTP requests across domains and does not solve the problem of JS calls between two pages in different domains
    • Jsonp does not return an HTTP status code when a call fails
    • There are certain security loopholes
  • Cors
    • The basic definition
      • Cors is a wC3 recognized standard for cross-origin resource sharing that addresses the limitation that Ajax can only be used in the same source
      • Both browsers and servers support this mode. The browser version cannot be later than Internet Explorer 10
    • Implementation mode (Cors is divided into simple request and complex request)
      • Simple request, as long as the following two conditions can be satisfied
      • Simple request, only need to add oneoriginThe browser automatically adds a field to the request header when it realizes it is a simple requestoriginfield
GET /cors HTTP/1.1
// Origin specifies the source (protocol + domain + port) from which the request comes. The server uses this value to decide whether to approve the request or not
Origin: http://api.bob.com
Host: api.alice.com
Accept-Language: en-US
Connection: keep-alive
User-Agent: Mozilla/5.0.Copy the code
- If the source specified by 'Origin' is not within the permitted scope, the server will return a normal HTTP response, and the browser will throw an error if it finds that the response header does not contain the 'access-Control-Allow-Origin' field, which is XMLHttpRequest's 'oner' The ror 'callback catches an error that is not recognized by the status code. If the Origin domain name is within the permitted range, the server returns a response with several header fieldsCopy the code
Access-Control-Allow-Origin: http://api.bob.com
Access-Control-Allow-Credentials: true
Access-Control-Expose-Headers: FooBar
Content-Type: text/html; charset=utf-8
// In the request header, there are three fields related to the Cors request, all beginning with access-Contronl
Copy the code
- Access-Contronl-Allow-Origin - This field is required. Its value is either the 'origin' field at the time of the request, or an '*' indicating that any domain name is accepted. If cookies are sent, 'access-contronl-allow-Origin' cannot be set to an asterisk and must specify an explicit domain name consistent with the requested web page, and c Ookie still follows the same origin policy, only the server domain name set cookies will be uploaded, other domain name cookies will not be uploaded, and (cross-domain) the original web code 'document.cookie' can not read the server domain name cookie information - Access-Control-Allow-Credentials - By default,Cookir is not included in the Cors request. True indicates that the server explicitly approved Cookir. Cookie can be included in the request and is a radio option Access-control-ecpose -Headers - This field is optional. In CORS requests, the 'getResponseHeader()' method of the 'XMLHttpRequest' object takes only six basic fields: 'cache-control', 'content-language', 'Content-Type', 'Expires',' last-Modified ', 'Pragma'. If you want to get other fields, you must specify them in 'access-Control-expose-headers'. The above example specifies that, 'getResponseHeader('FooBar')' can return the value of the 'FooBar' field - withCredentials attribute - Cors does not send Cookie information and HTTP authentication information by default. To send cookies to the server, specify the access-Control-allow-credentials field on the one handCopy the code
Access-Control-Allow-Credentials: true
Copy the code
- On the other hand, developers must enable the withCredentials attribute in their Ajax requests. Otherwise, browsers do not send cookies even when the server sends them The xhr.withCredentials = false; `Copy the code
var xhr = new XMLHttpRequest()
xhr.withCredentials= true
Copy the code
- ** non-simple requests ** - Non-simple requests are requests that have special requirements on the server, for example, the request method is' PUT 'or' DELETE ', or the Type of the 'Content-Type' field is' application/json '. Add an HTTP query, called a "preflight," in which the browser asks the server whether the domain name of the current web page is on the server's approved list and which HTTP verb and header fields are available. The browser issues a formal 'XMLHttpRequest' request, otherwise an error is reportedCopy the code
var url = 'http://api.alice.com/cors';
var xhr = new XMLHttpRequest();
xhr.open('PUT', url, true);
xhr.setRequestHeader('X-Custom-Header'.'value');
xhr.send();
Copy the code
- The HTTP request is a PUT, and sending a Custom x-custom-header automatically sends a "precheck" request, asking the server to confirm that it can do so. Here is the HTTP header for this "precheck" requestCopy the code
OPTIONS /cors HTTP/1.1
Origin: http://api.bob.com
Access-Control-Request-Method: PUT
Access-Control-Request-Headers: X-Custom-Header
Host: api.alice.com
Accept-Language: en-US
Connection: keep-alive
User-Agent: Mozilla/5.0.Copy the code
- "precheck" requests using the request method 'OPTIONS', indicating that the request is being queried. In addition to the Origin field, the precheck Request header contains two special fields - access-Control-request-method - which are required. Used to list the HTTP methods used by the browser for CORS requests, such as' PUT '. - access-Control-request-headers - This field is a comma-separated string that specifies the additional header field that the browser will send for CORS requests. The above example is' x-custom-header '- The server has passed the precheck request, and every browser CORS request, just like every simple request, will generate an 'Origin' field, and the server will respond with an 'Access-Control-Allow-Origin' header fieldCopy the code
// After prechecking the request, the browser's normal Cors request, the Origin field information, is automatically added
PUT /cors HTTP/1.1
Origin: http://api.bob.com
Host: api.alice.com
X-Custom-Header: value
Accept-Language: en-US
Connection: keep-alive
User-Agent: Mozilla/5.0.Copy the code
- Normal response of the server (' access-Control-allow-origin 'field must be included in every response)Copy the code
Access-Control-Allow-Origin: http://api.bob.com
Content-Type: text/html; charset=utf-8
Copy the code

What is synchronous and what is asynchronous

  • Single thread
    • JavaScript is a single-threaded language, so,JavaScript can only do one thing at a time, and single threading means that if there are multiple tasks at the same time, those tasks need to be queued before the next one can be executedBecause javaScript is a single-threaded execution, handle multiple tasks with time, queue, all tasks, a task has been completed before the next task to perform, if on a task execution time is very long (such as ajax request), then it will cause the next task waiting, seriously affect the user experience, so just can haveSynchronization taskandAsynchronous tasks
// Synchronize the code
function fun1() {
  console.log(1);
}
function fun2() {
  console.log(2);
}
fun1();
fun2();
/ / output
1
2
// If fun1 is an Ajax operation that takes some time, do we need to wait for fun1() to complete before executing fun2()?
Copy the code
  • Synchronization task
    • A synchronous task is,The next task can be executed only after the previous task is completedWhen we open the site, the rendering process of the site, such as the rendering of elements, is a synchronization task
// Synchronize the code
var num = 20;
console.log(num) // Output the result immediately

// Synchronize the code
var arr = [12.3224.34]
for(var i =0; i<arr.length; i++){console.log(arr[i])
}
// Synchronization code......... Much more, except callback(), Ajax and setTimeout, and the. Then () methods in Proimse, can be considered synchronized code
Copy the code
  • Asynchronous tasks
    • An asynchronous task is,A task that does not enter the main thread but enters the task queue will enter the main thread only if the task queue informs the main thread that an asynchronous task is ready to executeWhen we open a website, loading images, loading music, for example, is an asynchronous task
function fun1() {
  console.log(1);
}
function fun2() {
  console.log(2);
}
function fun3() {
  console.log(3);
}
fun1();
setTimeout(function(){
  fun2();
},0);
fun3();
 
/ / output
1
3
2
Copy the code
  • How asynchrony works (EventLoop is the same thing)
    • How is asynchrony implemented in javaScriptCallbacks and event loopsAsynchronous tasks do not enter the main thread, but enter it firstAsynchronous task queueThe task queue is essentially a followFirst in, last out, last in, first outThe data structure, which is also an event queue, such as a file read operation, is an asynchronous task that is first added toAsynchronous task queueWhen I/O completes, it will be in the task queue,Add an event, indicating that the asynchronous task has finished and can enter the execution stack. However, the main thread may not be free for processing at this time. The main thread will read the asynchronous task after it finishes processing other tasksAsynchronous task queueIn the code, a single thread from the task queue, the process is a continuous loop, each time the stack is emptied, will be inTask queueIf there is no task, wait until there is a new task, if there is a task, then it will be taken out for execution, this cycle process, is calledEvent loop
    • In summary
      • All synchronization tasks are executed on the main thread as a stack
      • In addition to the main thread, there is a task queue in which an event is placed whenever an asynchronous task has a result
      • Once all asynchronous tasks in the execution stack are completed, the system reads the task queue to check whether there are asynchronous tasks. After finishing the waiting state, the system enters the execution stack and starts execution
      • The main thread repeats all three steps

What is the difference between HTTP and HTTPS?

  • What is the HTTP protocol
    • HyperText Transfer Protocol (HTTP) is an application-layer Protocol for distributed, collaborative and hypermedia information systems. HTTP is the basis for data communication on the World Wide Web
    • HHTTP is a standard (TCP) for client end (user) and server end (web site) requests and responses. By using a web browser, web crawler, or other tool, a client initiates an HTTP request to a specified port (default port 80) on the server. We call this client a user Agent. The answering server stores resources such as HTML files and images. We call this reply server the Origin Server. There may be multiple “middle tiers” between the user agent and the source server, such as a proxy server, gateway, or tunnel
    • The HTTP client issues a request to create a TCP connection to the server’s specified port (default: port 80). The HTTP server listens for client requests on that port. Once a request is received, the server returns a status to the client, such as “HTTP/1.1 200 OK”, along with what is returned, such as the requested file, error message, or other information
  • Difference between HTTP and HTTPS
    • Data transmitted through HTTP is unencrypted and displayed in plain text. Privacy information transmitted through HTTP is very insecure. In order to ensure that information can be encrypted for transmission, Secure Sokets (SSL) are designed on the basis of HTTP The Layer protocol encrypts data transmitted through HTTP, thus giving birth to HTTPS
    • HTTPS is a network protocol that uses SSL and HTTP to encrypt transmission and authenticate identity. It is more secure than HTTP
    • The difference between the following
      • For HTTPS, you need to apply for a certificate from a CA. Generally, a few free certificates cost a certain amount
      • HTTP is a hypertext transfer protocol. Information is displayed in plain text, but HTTPS encrypts data transmission using SSL
      • HTTP and HTTPS use completely different connections, and the default port is 443
      • HTTP connection is also very simple, is stateless,HHTPS protocol is SSL+HTTP protocol to build encrypted transmission, identity authentication network protocol, more secure than HTTP protocol

7. What are the common HTTP status codes and what do they mean

  • Status code type
    • 1XX: Indicating message – indicating that the request has been received and processing continues
    • 2xx: Success: The request is successfully received, understood, or accepted
    • 3xx: Redirect – Further action must be taken to complete the request
    • 4XX: Client error – The request has a syntax error or the request cannot be implemented
    • 5xx: Server side error — the server failed to fulfill a valid request
  • Common status codes and meanings
401 Unauthorized // The Request is Unauthorized. This status code must be used with the www-Authenticate header field using 403 Forbidden // The server received the request but refused to provide the service 404 Not Found // The requested resource did Not exist, eg: An incorrect URL is entered. 500 Internal Server Error // An unexpected Error occurs on the Server. 503 Server Unavailable // The Server cannot process requests from the clientCopy the code

What is the three-way handshake for TCP connections?

  • First handshake: When establishing a connection, the client sends a SYN packet (SYN = J) to the server and enters the SYN_SENT state, waiting for confirmation from the server. SYN: Synchronize Sequence Numbers
  • Second handshake: After receiving a SYN packet, the server must acknowledge the client’s SYN (ACK = J +1) and send a SYN packet (ACK = K). In this case, the server enters the SYN_RECV state
  • Third handshake: After receiving the SYN+ACK packet from the server, the client sends an ACK packet (ACK = K +1) to the server. After the packet is sent, the client and the server enter the ESTABLISHED state (TCP connection is successful) and complete the three-way handshake

ES6

1. Array expansion

  • Extended operator
  • Arrar.from()
  • Arrar.of()
  • Instance copyWithin ()
  • Instances find() and findIndex()
  • Examples of the fill ()
  • Values instance entrens keys () () ()
  • Instance inculecs ()
  • Instance flat (), flatMap ()

2, String extension & method

  • The for of traverse
    • You can iterate using the syntax below, and you can iterate for ofoxFFFThe code of points
for (let codeString of  'foo') {console.log(codeString)
}
// "f"
// "o"
// "o"
Copy the code
  • Template string
    • Is an enhanced version of a string, identified by backquotes (‘), that can be used as a regular string, can define multiple strings, and can embed variables in the string
$('#result').append(`
  There are <b>${basket.count}</b> items
   in your basket, <em>${basket.onSale}</em>
  are on sale!
`);
Copy the code
  • includes()
    • Returns a Boolean value indicating whether the parameter string was found
let s = 'Hello world! ';
s.includes('o') // true
// The second argument represents the starting position of the query
s.includes('o'.6) // false
Copy the code
  • startsWith()
    • Returns a Boolean value indicating whether the argument string is at the beginning of the original string
let s = 'Hello Word! ';
s.startsWith('Hello') // true
// The second argument represents the starting position of the query
s.endsWith('Hello'.5) // true
Copy the code
  • endsWith()
    • Returns a Boolean value indicating whether the argument string is at the end of the original string
let s = 'Hello world! ';
// The second argument, for the first n arguments, and the other two methods, for the end of a character from the NTH position
s.startsWith('world'.6) // true
s.endsWith('Hello'.5) // true
Copy the code
  • repeat()
    • Returns a new string indicating how many times the original string is repeated
'x'.repeat(3) // "xxx"
'hello'.repeat(2)// "hellohello"

// The argument is rounded if it is a decimal
'na'.repeat(2.9) // "nana"

// If the repeat argument is negative, or lfinity, an error is reported
'na'.repeat(Infinity)
// RangeError
'na'.repeat(-1)
// RangeError

// However, if the argument is a decimal between 0 and -1, it is the same as 0, because the integer is rounded first. If the decimal number between 0 and -1 is rounded to -0, repeat is regarded as 0
'na'.repeat(-0.9) / / ""

// The argument is NaN equals 0
'na'.repeat(NaN) / / ""

// If the repeat argument is a string, it is converted to a number first
'na'.repeat('na') / / ""
'na'.repeat('3') // "nanana"
Copy the code

Obejct extension & Method

  • Property and method abbreviations
    • Attribute shorthand
let obj = 'is object';
let objName = {obj}
objName // {obj:'is object'}

/ / equivalent to the
const objName = {obj:obj}
/ / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * line * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
function fn (x,y){
    return {x+y}
}
/ / is equivalent to
function fn (x,y){
    return {x:x,y:y}
}
fn(1.2) // Object {x:1,x:2}
Copy the code
  • Methods shorthand
const Person={
    sayHi(){
        console.log('I'm the sayHi method in the Person object')}}/ / equivalent to the
const Person={
    sayHi:function(){
        console.log('I'm the sayHi method in the Person object')}}/ / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * line * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
let url = 'htpps://www.baidu.com'
const ToUrl ={
    url, 
    erros: () {console.log('url is errors')}}/ / equivalent to the
let url = 'htpps://www.baidu.com'
const ToUrl ={
     // Equivalent to :url :url
    url,
    Erros :function() {}
    erros: () {console.log('url is errors')}}Copy the code
- Application Scenario 1(' This can be done in commonJS ')Copy the code
let ms = {};

function getItem (key) {
  return key in ms ? ms[key] : null;
}

function setItem (key, value) {
  ms[key] = value;
}

function clear () {
  ms = {};
}

module.exports = { getItem, setItem, clear };
/ / is equivalent to
module.exports = {
  getItem: getItem,
  setItem: setItem,
  clear: clear
};
Copy the code
  • Application Scenario 2(Property getters and property setters can also be used in this way)
const cart = {
  _wheels: 4,

  get wheels () {
    return this._wheels;
  },

  set wheels (value) {
    if (value < this._wheels) {
      throw new Error('Too small! ');
    }
    this._wheels = value; }}Copy the code
  • Notes (You cannot use abbreviations in constructors)
const obj = {
  f() {
    this.foo = 'bar'; }};new obj.f() / / an error
Foo. F cannot be used as a constructor because f is shorthand for object methods
Copy the code
  • Property enumerable
    • Each attribute has a description of the object, this property is used to control the behavior of, obj. GeyOwnPropertyDescriptor method, can obtain the attribute description of object, describe eumerable attribute of the object, called an enumerable, if this property is false, means that certain actions will ignore the current sex
let obj = { foo : 123}
Object.getOwnPropertyDescriptor(obj, 'foo')
//  {
// value: 123,
// writable: true,
// enumerable: true,
// configurable: true
/ /}
Copy the code
  • Property traversal
    • for in
      • for... inLoop over the object’s own and inherited enumerable properties (excluding Symbol properties)
    • Object.keys
      • Object.keysReturns an array containing the key names of all the enumerable attributes (excluding the Symbol attribute) of the object itself (excluding inheritance)
    • Object.getOwnPropertyNames(obj)
      • Object.getOwnPropertyNamesReturns an array containing the key names of all properties of the object itself (excluding the Symbol property, but including non-enumerable properties)
    • Object.getOwnPropertySymbols(obj)
      • Object.getOwnPropertySymbolsReturns an array containing the key names of all the Symbol properties of the object itself
    • Reflect.ownKeys(obj)
      • Reflect.ownKeysReturns an array containing all of the object’s own (not inherited) key names, whether they are symbols or strings or enumerable
    • Matters needing attention:
      • All five methods follow the same sequence rules for traversal of attributes
      • First, all numeric keys are iterated, sorted in ascending order
      • Next, all the string keys are iterated in ascending order by the time they were added
      • Finally, all Symbol keys are iterated in ascending order of time they were added
  • Object extension operator
    • Object extension operator, used to fetch all traversable properties of the parameter object and copy them into the current object
let obj = { a: { b: 1}};let { ...x } = obj;
obj.a.b = 2;
x.a.b / / 2
Copy the code
  • Since arrays are special objects, extension operators for objects can also be used for arrays
letfoo = {... ['a'.'b'.'c']}
foo
// {0: "a", 1: "b", 2: "c"}
Copy the code
  • If the extension operator is followed by an empty object, it has no effect
{... {},a: 1}
// { a: 1 }
Copy the code
  • If the extension operator is not followed by an object, it is automatically converted to an object
// the same as {... Object(1)}
{..1.} / / {}
Copy the code
  • In the code above, the extended operator is followed by the integer 1, which is automatically converted to a numeric type, and returns an empty object because the object does not have the property
// the same as {... Object(true)}{... true}/ / {}

// the same as {... Object(undefined)}{... undefined}/ / {}

// the same as {... Object(null)}{... null}/ / {}
Copy the code
  • If the operator is followed by a string, it is automatically converted to an array-like object, so it does not return an empty object
{...'hello'}
// {0: "h", 1: "e", 2: "l", 3: "l", 4: "o"}
Copy the code
  • Object extension operators are equivalent to usingObject.assign()methods
letaClone = { ... a };/ / is equivalent to
let aClone = Object.assign({}, a);
// If you want to clone an object completely and copy its prototype properties, you can use the following methods
/ / write one
const clone1 = {
  __proto__: Object.getPrototypeOf(obj), ... obj };/ / write two
const clone2 = Object.assign(
  Object.create(Object.getPrototypeOf(obj)),
  obj
);

/ / writing three
const clone3 = Object.create(
  Object.getPrototypeOf(obj),
  Object.getOwnPropertyDescriptors(obj)
)
Copy the code

4. Deconstruct assignment

  • Object destructuring assignment
    • Object deconstruction assignment is used to take values from an object. It is equivalent to assigning all the traversable but unread properties of the target object to the specified object. All the keys and their values are copied to the new object
    • Be able toundefinedandnullConvert, because these two cannot be converted to objects
let { ...z } = null; // Runtime error
let { ...z } = undefined; // Runtime error
Copy the code
  • The destruct assignment must be the last argument, or an error will be reported
 let{ ...x, y, z } = someObject; // Syntax error
let{ x, ... y, ... z } = someObject;// Syntax error
Copy the code
  • A copy in a deconstructed assignment is a shallow copy
let obj = { a: { b: 1}};let { ...x } = obj;
obj.a.b = 2;
x.a.b / / 2
Copy the code

5. Set and Map data structures

  • set
    • Similar to the form of an array, but with unique members and no duplicate values, a Set itself is a constructor that generates a Set data structure
const s = new Set(a); [2.3.5.4.5.2.2].forEach(x= > s.add(x));

for (let i of s) {
  console.log(i);
}
// 2 3 5 4
Copy the code
  • Traversal operations that can be performed
    • Set.prototype.keys(): returns a traverser for key names
    • Set.prototype.values(): returns a traverser for key values
    • Set.prototype.entries(): returns a traverser for key-value pairs
    • Set.prototype.forEach(): Iterates through each member using the callback function
  • map
    • It is essentially a combination of key-value pairs (Hash structures), but traditionally only strings are used as keys, which imposes significant limitations on how they can be used
const data = {};
const element = document.getElementById('myDiv');

data[element] = 'metadata';
data['[object HTMLDivElement]'] // "metadata"
Copy the code
  • Traversal methods
    • The Map structure natively provides three traverser generating functions and one traversal method
    • Map.prototype.keys(): returns a traverser for key names
    • Map.prototype.values(): returns a traverser for key values
    • Map.prototype.entries(): returns a traverser for all members
    • Map.prototype.forEach(): Traverses all Map members