Create, add, remove, and copy DOM nodes

1. Create the element node

The document.createElement() method is used to create an element, takes a parameter, the tag name of the element to be created, and returns the element node to be created

 var div = document.createElement("div"); // Create a div element
 div.id = "myDiv"; // Set the div id
 div.className = "box"; // Set the div class
Copy the code

After the element is created, it is also added to the document tree

2. Add element nodes

The appendChild() method is used to add a node to the end of the childNodes list, returning the element node to be added

 var ul = document.getElementByIdx("myList"); / / the ul
 var li = document.createElement("li"); / / create the li
 li.innerHTML = "Item 4"; // Add text to li
 ul.appendChild(li); // Add li to the end of ul child node
Copy the code

The apendChild() method can also add an existing element, moving it from its original position to a new one

 var ul = document.getElementById("myList"); / / the ul
 ul.appendChild(ul.firstChild); // Move the first ul element node to the end of the ul child node
Copy the code

The sertBefore() method, if you do not want to insert a node at the end but want to place it at a specific position, takes two arguments, the first the node to insert and the second the reference node, which returns the element node to be added

 var ul = document.getElementById("myList"); / / the ul
 var li = document.createElement("li"); / / create the li
 li.innerHTML= "Item 4"; // Add text to li
 ul.insertBefore(li,ul.firstChild); // add li to the first child of ul
Copy the code
 var ul = document.getElementById("myList"); / / the ul
 var li = document.createElement("li"); / / create the li
 li.innerHTML= "Item 4"; // Add text to li
 ul.insertBefore(li,ul.lastChild); // Add li before the last child of ul, including the text node
Copy the code
 var ul = document.getElementById("myList"); / / the ul
 var li = document.createElement("li"); / / create the li
 li.innerHTML= "Item 4"; // Add text to li
 var lis = ul.getElementsByTagName("li") // Get the set of all Li's in ul
 ul.insertBefore(li,lis[1]);// Add li before the second li node in ul
Copy the code

After adding:

3. Remove the element node

The removeChild() method, used to remove a node, takes an argument, the node to be removed, and returns the removed node. Note that the removed node is still in the document, but its location is no longer in the document

 var ul = document.getElementById("myList"); / / the ul
 var fromFirstChild = ul.removeChild(ul.firstChild); // Remove the first child of ul
Copy the code
 var ul = document.getElementById("myList"); / / the ul
 var lis = ul.getElementsByTagName("li") // Get the set of all Li's in ul
 ul.removeChild(lis[0]);// Remove the first li, different from the above, considering browser differences
Copy the code
4. Replace element nodes

The replaceChild() method, used to replace a node, takes two arguments, the first is the node to be inserted and the second is the node to be replaced, returning the node to be replaced

 var ul = document.getElementById("myList"); / / the ul
 var fromFirstChild = ul.replaceChild(ul.firstChild); // Replace the ul first child node
Copy the code
 var ul = document.getElementById("myList"); / / the ul;
 var li = document.createElement("li"); / / create the li
 li.innerHTML= "Item 4"; // Add text to li
 var lis = ul.getElementsByTagName("li") // Get the set of all Li's in ul
 var returnNode = ul.replaceChild(li,lis[1]); // Replace the second li with the created li
Copy the code
5. Copy the node

CloneNode () method, used to copy a node, takes a Boolean argument, true for deep copy (copy the node and all its children), false for shallow copy (copy the node itself, not the children)

 var ul = document.getElementById("myList"); / / the ul
 var deepList = ul.cloneNode(true); / / copy
 var shallowList = ul.cloneNode(false); / / shallow copy
Copy the code

Pop (), push(), shift(), unshift(

Shift (): Removes the first element from the collection and returns the value of that element. Unshift (): adds one or more elements to the beginning of the collection and returns the new length push(): adds an element to the collection and returns the new length POP (): removes the last element from the collection and returns the value of this element.

3. Thousandth split number: 1234567890.11 -> 1,234,567,890.11

Method 1: Numeric type

let str = 1234567890.11;
str.toLocaleString() / / 1234567890.11
Copy the code

Method 2: String type

let reg = /(\d)(? = (? :\d{4})+$)/g;
let str = '1234567890.11';
let target = str.replace(reg, '$1'); / / 1234567890.11
Copy the code

4, array to multiple ways to achieve

It reloads by iterating through the new array

	/ / 1
    Array.prototype.unique1 = function(){
        var arr1 = []; // Define a new array
        for(var i=0; i<this.length; i++){if(arr1.indexOf(this[i]) == -1) {// Check whether the target array exists in the original array
            arr1.push(this[i]); }}return arr1;
    }
    
    / / 2
    Array.prototype.unique2 = function(){
      var hash = {}; // Define a hash table
      var arr1 = []; // Define a new array
      for(var i=0; i<this.length; i++){if(! hash[this[i]]){
          hash[this[i]] = true;
          arr1.push(this[i]); }}return arr1;  
    }
Copy the code

Set implements deduplication

const a=Array.from(new Set([1.1.2.2.3.4.5.6]))
console.log(a); / / 6
Copy the code

5. What are the differences between simple and complex requests for cross-domain use of CORS?

1. Simple requests

A simple request looks something like this:

The HTTP method is one of the following

HEAD // A HEAD request is essentially the same as a GET request, but a HEAD request contains no data, only HTTP header information GET POSTCopy the code

HTTP header information does not exceed the following fields

Accept accept-language content-language last-event-id content-type, But only one of the following application/ X-www-form-urlencoded multipart/form-data text/plainCopy the code

The partial response header and explanation for a simple request are as follows:

Access-control-allow-origin (required) - Cannot be omitted, otherwise the request is treated as a failure. This controls the visibility of the data. If you want the data to be visible to anyone, you can fill in an "*". Access-control-allow-credentials (Optional) - This parameter indicates whether cookies are included in the request. There is only one optional value: true (must be lowercase). If cookies are not included, omit this item instead of filling in false. This should be consistent with the withCredentials property in the XmlHttpRequest2 object, which is true when withCredentials is true. When the withCredentials are false, this item is omitted. Otherwise, the request fails. Access-control-expose-headers (Optional) - This determines the additional information available to the getResponseHeader() method in the XmlHttpRequest2 object. In general, the getResponseHeader() method can only get the following information: Cache-control Content-language Content-type Expires Last-Modified Pragma When you need to access additional information, you need to specify this field and separate it with commasCopy the code

Any request that does not meet the above requirements is considered a complex request. A complex request contains not only a request containing communication content, but also a preflight request.

2. Complex requests

Complex requests look similar to simple requests on the surface, but the browser actually sends more than one request. The first one is a “pre-request”, and the server needs to return a “pre-response” as a response. A pre-request is actually a permission request to the server. The actual request is executed only when the pre-request is successfully returned.

The pre-request is sent in the form of OPTIONS, which also contains fields and contains two CORS specific items:

Access-control-request-method - This is the type of actual Request, which can be simple requests like GET, POST, PUT, DELETE, and so on. Access-control-request-headers - This item is a comma-separated list of the Headers used by the complex Request.Copy the code

Obviously, this pre-request is actually a permission request for a later actual request, and in the pre-response returned, the server should reply to both items to let the browser determine whether the request can be successfully completed.

Partial response headers and explanations for complex requests are as follows:

Access-control-allow-origin (required) - As with simple requests, a field must be included. Access-control-allow-methods (required) - This is a comma-separated list of responses to access-Control-request-methods in a pre-request. Although a client may only request one method, the server can still return all allowed methods for the client to cache. Access-control-allow-headers (must be included if the pre-request contains access-Control-request-headers) -- This is a response to the pre-request for access-Control-request-headers. As above, it is a comma-separated list that returns all supported headers. If you don't want to make too much of a decision on this layer, you can actually get Access to access-Control-request-headers from the request header. Set the value to access-Control-allow-headers. Access-control-allow-credentials (Optional) - The same as in simple requests. Access-control-max-age (Optional) - Cache time in seconds. The sending of pre-requests is not a free lunch and should be cached whenever possible.Copy the code

Once the pre-response arrives as expected and all requested permissions are satisfied, the actual request is sent.

6. Know sorting algorithms? Talk about bubble sort and quicksort

Bubble sort:

Compare adjacent elements. If the first one is bigger than the second, swap them both. Do the same for each pair of adjacent elements, starting with the first pair and ending with the last pair. At this point, the last element should be the largest number. Repeat this step for all elements except the last one. Keep repeating the above steps for fewer and fewer elements at a time until there are no more pairs to compare.

 // Bubble sort
  const bubbleSortOne = (arr) = > {
    for (let i = 0; i < arr.length - 1; i++) {
      for (let j = i + 1; j < arr.length; j++) {
        if (arr[i] > arr[j]) {
          // Switch places[arr[i], arr[j]] = [arr[j], arr[i]]; }}}return arr;
  };

  console.log(bubbleSortOne([2.1.3.5.6.4])); // [1, 2, 3, 4, 5, 6]
Copy the code
Quicksort:

Start by taking a number from the sequence as a “base”. Partition process: put all numbers greater than the base to the right of the base and all numbers less than or equal to the base to the left of the base. Repeat the second step for the left and right intervals until each interval has only one number.

var quickSort = function(arr) {
    if (arr.length <= 1) { return arr; }
    var pivotIndex = Math.floor(arr.length / 2);   // Base position (theoretically optional)
    var pivot = arr.splice(pivotIndex, 1) [0];  / / reference number
    var left = [];
    var right = [];
    for (var i = 0; i < arr.length; i++){
        if (arr[i] < pivot) {
            left.push(arr[i]);
        } else{ right.push(arr[i]); }}return quickSort(left).concat([pivot], quickSort(right));  // Link left array, base array, right array
};
Copy the code