“This article has participated in the good article call order activity, click to see: back end, big front end double track submission, 20,000 yuan prize pool for you to challenge!”

Summarize some front-end JS knowledge, the notes will be organized to share with you, some knowledge will often be asked in the front-end interview, so make a record, hope to help you, if there is any problem, can point out, will actively correct. If you like, you can like or leave a message and I will continue to update the interview questions ~~~~, thank you ~~~

1, before ++, after ++, difference?

var i=2 ;
a = i++ // Assign the value of I to a, i.e. a = I, and then execute I = I + 1; 2
a = ++i // Assign the value of I +1 to a, i.e. a = I +1, and then execute I = I +1; 3
console.log(a)
Copy the code

[Conclusion] :

The first ++ is self-adding and then calculating, and the second ++ is self-adding and then calculating

1: Preposition ++ is to assign the value after itself +1 to the variable, while adding 1 to itself;

2: post ++ is to assign its own value to the variable, and then add 1 to itself;

What data types do JS have?

Js basic data type undefined null Boolean number string Bigint Js reference type object Array function ES6 basic data type additional symbol

3, js judgment type?

2. Instanceof does not detect the number, Boolean, string, undefined, null, symbol types. Instancof is often used to detect complex types and construstor relationships. Constructor null, undefined, does not construstor a method of construstor. But the point to its constructor is can be changed, so insecure. 4, the Object prototype. ToString. Call all types can be judged

4. How to detect data types?

1,typeofEx. :console.log(typeof true) // boolean

2,instanceofEx. :console.log([1.2] instanceof Array) // true

3,constructorEx. :console.log([1.2].constructor === Array) / /ture4,Object.prototype.toString.callEx. :Object.prototype.toString.call([1.2]) / / /object Array]
Copy the code

5, Js array method

Add pop() to the end of push() remove shift() header remove unshift() header Add sort sort Reverse concat() link two or more arrays slice() var Arr =[1,2,3,4,5] console.log(arr.slice(1)) //[2,3,4,5] select a new array consisting of all elements from 1 to the end Splice () splice(index,howmany,item1,… Howmany arguments: Must, the number of items to be deleted, if 0, do not delete item1,… Var arr=[1,2,3,4,5] console.log(arr.splice(2,1,”hello”)); //[3] return a new array console.log(arr); //[1,2,”hello”,4,5] indexOf() and lastIndexOf() (forEach() (ES5) map() (ES5) filter() (ES5) every() (ES5) Some () (ES5新) reduce() and reduceRight() (ES5新)

What is the difference between array.splice () and array.slice () methods in JS?

Without further ado, let’s take our first example:

var arr=[0.1.2.3.4.5.6.7.8.9];// Set an array
console.log(arr.slice(2.7));/ / 2,3,4,5,6
console.log(arr.splice(2.7));/ / 2,3,4,5,6,7,8
// From this, we can simply infer the meaning of the two parameters of the function,Slice (start,end) The first parameter indicates the start position and the second parameter indicates the truncated position (not including the position) splice(start,length) The first parameter indicates the start position and the second parameter indicates the truncated lengthCopy the code

Moving on to the second one:

var x=y=[0.1.2.3.4.5.6.7.8.9]
console.log(x.slice(2.5));/ / 2 and 4
console.log(x); [0.1.2.3.4.5.6.7.8.9The original array is unchanged// Next test splice in the same way
console.log(y.splice(2.5));/ / 2,3,4,5,6
console.log(y);//[0,1,7,8,9] shows that the values in the original array are excluded
Copy the code

Slice and splice both cut from an array, but there are significant differences between them. The first argument to slice and splice is the start of the cut, the second argument to slice is the end of the cut (not included), and the second argument to splice is the start of the cut Slice does not change the size of the original array, and splice will delete the intercepts directly from the original array! Slice doesn’t change the array, splice changes the array

7. Numerical conversion

Json.parse () turns the JSON object json.stringify () turns the JSON String String(),toString() turns the String type Number parseInt() turns the String type split String turns the array join Array to string

8, what is cross-domain, common cross-domain

The browser follows the same origin policy when obtaining data, so when accessing non-same origin resources, it needs to cross domains. Common cross-domain methods include JSONP, A IMG SRC CORS, and the same origin policy: same protocol, port, and domain name security policy. Use the callpack callback function to get the value

function callbackFunction(){ alert("Rollback");
}
var script=document.createElement("script");
script.src="http://frergeoip.net.json/?callback=callbackFunction";
Copy the code

The principle of CORS: when the amount of transmitted data is large and the form of GET can not be made, CORS cross-domain can be used. The principle of CORS is to define a cross-domain access mechanism, so that Ajax can achieve cross-domain access. Cors allows web applications on one domain to submit cross-domain Ajax requests to another domain. Implementing this feature is as simple as sending a response header from the server. Jsonp is a GET form and carries limited information, so CORS is the best choice when the information is large.

9. HTTP protocol:

The HTTP protocol defines the communication mode of file transfer between the server and the client. There are various methods (all methods in uppercase) to request HTML, CSS, JS image files and other resources on the server. The explanations of each method are as follows: GET (GET) requests to obtain the resource identified by the Request-URI. POST (POST) appends new data to the resource identified by the Request-URI. Request The response message header to obtain the resource identified by the request-URI. — Obtain the header of the packet. PUT (PUT) Requests the server to store a resource. DELETE (DELETE) requests the server to DELETE the resource identified by the Request-URI. DELETE (TRACE) requests the server to send back the received Request information. For testing or diagnosing CONNECT (CONNECT) reserved for future use of OPTIONS (OPTIONS) requests to query server performance, or query OPTIONS and requirements related to resources. 200 Request succeeded 301 Resource (web page, etc.) is permanently transferred to another URL 404 Requested resource does not exist 500 internal server error

10. HTTP status code

If the HTTP header has been sent, the server will return this message to acknowledge that the HTTP header has been sent. 201 The Created request is successful and the server has Created a new resource. 202 Accepted The request but has not processed it. 301 Moved Permanently to a new location. 302 Found Temporary redirection. 303 See Other Temporary redirects and always requests a new URI using GET. 304 Not Modified The requested page has Not been Modified since the last request. 400 Bad Request The server does not understand the format of the Request. The client should not attempt to make the Request again with the same content. 401 Unauthorized Requests Are not authorized. 403 Forbidden Forbidden access. 404 Not Found Failed to find how to match the resource URI. 500 Internal Server Error Indicates the most common Server Error. 503 Service Unavailable The server is temporarily unable to process the request (possibly due to overload or maintenance).

What do you understand about closures?

Closures are used primarily to design private methods and variables. The advantage of closure is that it can avoid the pollution of global variables. The disadvantage is that the closure will be resident in memory, which will increase the memory usage. Improper use is easy to cause memory leakage. Closures have three features: 1. Functions can be nested; 2. Functions can refer to external parameters and variables 3. Garbage collection parameters and variables will not be recycled closure USES 1 cache suppose we have a process is very time consuming function object, each invocation will take a long time, then we will need to calculate the value of the stored, when this function is called, in the first place in the cache lookup, if can’t find, is calculated, Then update the cache and return the value, or if it is found, simply return the value. Closures do this because they do not release external references, so that the values inside the function can be preserved. An example of encapsulation is that the variables inside the person cannot be accessed outside of the person, but are accessed by providing a closure:

var person = function(){    
    // The variable is scoped inside the function and cannot be accessed from outside
    var name = "default";              
    return {    
       getName : function(){    
           return name;    
       },    
       setName : function(newName){ name = newName; }}} (); print(person.name);// Direct access, the result is undefined
print(person.getName());    
person.setName("abruzzi");    
print(person.getName()); 
Copy the code

12. How do I stop events from bubbling?

Ev. cancelBubble = true; The IE ev. StopPropagation ();

How do I prevent default events?

(1) return false. (2) ev.preventDefault();

14. Event proxy

Event agent means that the parent box is bound to the event, and then the subbox triggers the event. Due to the event bubble, the parent box event is also triggered. In this case, the parent box’s time handler can obtain the target time through the srcElement or target attribute, and handle it accordingly

15. Add, delete, replace methods inserted into a node?

1Create a new node createElement()// Create a concrete element
createTextNode() // Create a text node
 
2AppendChild () add, remove, replace, insert appendChild()/ / add
removeChild() / / remove
replaceChild() / / replace
insertBefore() / / insert
 
3) to find the getElementsByTagName ()// By label name
getElementsByName() // Pass the value of the element's Name attribute
getElementById() // By element Id, unique
Copy the code

What is the difference between document Load and Document Ready?

$().ready(function) = $().ready(function) = $().ready(function)

17. What are the event flow models in Javascript?

“Capture” : from bottom to top, the window, the document, the document. The documentelment get HTML document, the body,… . The target element

“Events bubble” : from the bottom up: vice versa

DOM event flow: three phases: event capture, target phase, and event bubble



Dom event class:

Dom0  element.onclick=function(){} DOM2 element. AddEventlistener (" click ",function(){}, flase) the DOM3 element. AddEventlistener (" keyup ",function(){},flase) event.preventdefault () preventdefault event.stoppropagation () prevent bubble event.currenttarget () Event agent event.target the currently clicked elementCopy the code

What is the difference between null and undefined?

Null is an object that represents “nothing” and is converted to a value of 0; Undefined is an original value representing “nothing” and is converted to NaN. When the declared variable has not been initialized, the default value of the variable is undefined. Null is used to indicate an object that does not yet exist. It is often used when a function attempts to return an object that does not exist.

19, What is the difference between call() and.apply()?

Similarity: Both methods have exactly the same effect. They both change the direction of this

Differences: Methods pass different parameters

Object.call(this,obj1,obj2,obj3)

Object.apply(this,arguments)

Apply() takes two arguments, one is the scope (this) to run the function, and the other is an array of arguments.

The first argument of the Call() method is the same as that of the apply () method, but the arguments passed must be listed.

20. Principle of MVC and MVVM mode:

Why should JS distinguish between microtasks and macro tasks?

(1) Js is single-threaded, but asynchronous (2) microtasks and macro tasks are asynchronous tasks, they all belong to the same queue (3) Macro tasks are generally: Script, setTimeout, setInterval, setImmediate (4) microtasks: Native Promise (5) executes microtasks first when it encounters microtasks, then executes the next macro task if no microtasks are available, and executes microtasks one by one if any

22. SetTimeout and setInterval

//setTimeout is executed after 3 seconds
 setTimeout(function(){
 alert(123)},3000)

//setInterval is executed every three seconds
 setInterval(function(){
 alert(1121222)},3000)
// Both executions are performed asynchronously
Copy the code

Deep copy shallow copy

The fundamental difference between a deep copy and a shallow copy is whether you actually get a copy of an object, rather than a reference.

If B has copied A, change A and see if B has changed:

If B follows also changed, it is a shallow copy, take a short hand! (Change the same value in the heap memory)

If B doesn’t change, it’s a deep copy, and it’s on its own! (change different values in the heap memory)

  var a = [1.2.3.4.5];
  var b = a;
  a[0] = 2
  console.log(a);/ / (2, 2, 3, 4, 5]
  console.log(b);//[2,2,3,4,5] ////b varies with a
Copy the code

Deep copy implementation:

  var a = [{"name":"weifeng"}, {"name":"boy"}];
  var a_copy =[].concat(JSON.parse(JSON.stringify(a)));/ / copy
  a_copy[1].name = "girl"
  console.log(a);//[{"name":"weifeng"},{"name":"boy"}]
  console.log(a_copy );//[{"name":"weifeng"},{"name":"girl"}]  
Copy the code

24. Rearrange and redraw

Reflux: When part (or all) of a render tree needs to be rebuilt due to changes in the element’s size, layout, hiding, etc. This is called reflow. Every page needs to be reflow at least once, the first time the page is loaded, which is bound to happen because the Render tree is being built. During backflow, the browser disables the affected part of the rendered tree and reconstructs that part of the rendered tree. When the backflow is complete, the browser redraws the affected part onto the screen, a process known as redrawing. Redraw: When some element in the Render tree needs to update attributes that only affect the appearance and style of the element, not the layout, such as background-color. It’s called a redraw. Difference: backflow inevitably causes redrawing, but redrawing does not necessarily cause backflow. For example, only when the color changes will only redraw without backflow. When the page layout and geometry changes, such as adding or removing visible DOM elements, element position changes, element size changes — margins, fills, borders, width and height, content changes.

25, shake and throttling?

In front end development, we often need to bind events that keep firing, such as resize, Scroll, mousemove keyup, etc., but sometimes we don’t want to execute functions that often while the events are firing.

How do we usually solve this situation? Generally speaking, damping and throttling are better solutions. 1. Anti-shaking: the function is executed n seconds after the event is triggered. If the event is triggered again within n seconds, the execution time of the function will be recalculated. Application scenario (suitable for responding to multiple events only once) : Add an anti-shake function to the button to prevent multiple submission of the form. Judge whether scroll slides to the bottom; For AJAX validation of continuous input boxes, using function stabilization can effectively reduce the number of requests. Here is a scenario: now listen to an input box, text changes after triggering the change event. If the keyUp event is used directly, the change event is frequently triggered. The change event is triggered only when the user’s input ends or is paused. The so-called anti-shaking means that the function can only be executed once within n seconds after the event is triggered. If the event is triggered again within N seconds, the execution time of the function will be recalculated.

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>Document</title>
</head>
<body>
    <input type="text" id="input1">
</body>
<script>
    const input1 = document.getElementById('input1')
//1. If you do not add shake, the change event will always be triggered
    input1.addEventListener('keyup'.function(){
            console.log(input1.value)
    })

//2. Simple implementation of anti-shaking
    let timer = null
    input1.addEventListener('keyup'.function(){
        if(timer){
            clearTimeout(timer)
        }
        timer = setTimeout(() = > {
            // The simulation fires the change event
            console.log(input1.value)
            // Clear the timer
            timer = null
        }, 1000)})//3
    function debounce(fn, delay = 50){
        // The timer is in a closure and cannot be modified by others
        let timer = null
        return function(){
            if(timer){
                clearTimeout(timer)
            }
            timer = setTimeout(() = > {
                fn.apply(this.arguments)
                timer = null
            }, delay)
        }
    }
    input1.addEventListener('keyup', debounce(function(){ 
        console.log(input1.value)
    }, 600))
</script>
</html>
Copy the code

Then the anti-shaking function after encapsulation is:

function debounce(fn, delay = 50){
        let timer = null  // The timer is in a closure and cannot be modified by others
        return function(){
            if(timer){
                clearTimeout(timer)
            }
            timer = setTimeout(() = > {
                fn.apply(this.arguments)
                timer = null
            }, delay)
        }
    }
Copy the code

2. Throttling: Continuously sent events are executed only once in n seconds. Application scenarios (suitable for a large number of events to be triggered evenly by time allocation) : DRAG and drop DOM elements; Canvas brush function. Now give a scene: drag an element, want to get the element to be dragged position at any time. If the drag event is used directly, it is triggered frequently and can easily cause a lag. With throttling, it triggers at regular intervals, no matter how fast the drag is. Throttling is when events are fired continuously but the function is executed only once in n seconds. Throttling dilutes the frequency of function execution.

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>Document</title>
    <style>
        #div1{
            border: 1px solid #ccc;
            width: 200px;
            height: 100px;
        }
    </style>
</head>
<body>
    <div id = "div1" draggable="true">Can drag and drop</div>
    <script>
        const div1 = document.getElementById('div1')
  
  //1
        let timer = null
        div1.addEventListener('drag'.function(e){
            if(timer){
                return
            }
            timer = setTimeout(() = > {
                console.log(e.offsetX, e.offsetY)
                timer = null // Set the timer to null after the timer has executed
            }, 1000)})//2. Wrap the throttling tool
        function throttle(fn, delay = 100){
            let timer = null
            return function(){ 
                if(timer){
                    return
                }
                timer = setTimeout(() = > {
                    fn.apply(this.arguments)
                    timer = null
                },delay)
            }
        }
        div1.addEventListener('drag', throttle(function(e){ // The parameter e is passed to the function returned by the throttle function
                console.log(e.offsetX, e.offsetY)   
        },200))
    </script>
</body>
</html>
Copy the code

Then the encapsulated throttling function is:

function throttle(fn, delay = 100){
            let timer = null
            return function(){ 
                if(timer){
                    return
                }
                timer = setTimeout(() = > {
                    fn.apply(this.arguments)
                    timer = null
                },delay)
            }
        }
Copy the code

What happens in the process of a page from the input URL to the page loading display?

It is divided into four steps: (1), when sending a URL request, regardless of whether the URL is the URL of the Web page or the URL of each resource on the Web page, the browser will start a thread to process the request and start a DNS query on the remote DNS server. This enables the browser to obtain the IP address corresponding to the request. (2), the browser and the remote Web server establish a TCP/IP connection through the TCP three-way handshake negotiation. The handshake consists of a synchronization packet, a synchronization – reply packet, and a reply packet. These three packets are transmitted between the browser and the server. The handshake is first attempted by the client to establish communication, then the server responds and accepts the request from the client, and finally the client sends a packet indicating that the request has been accepted. (3), once the TCP/IP connection is established, the browser sends an HTTP GET request to the remote server over that connection. The remote server finds the resource and returns it with an HTTP response. An HTTP response status with a value of 200 indicates a correct response. (4) at this point, the Web server provides resource services and the client starts to download resources. In short, the browser parses the HTML to generate a DOM Tree, then it generates a CSS Rule Tree based on the CSS, and javascript can manipulate the DOM based on the DOM API. What happens between entering the URL and receiving it by the browser?

27. Talk about the three-way handshake strategy for TCP transmission

In order to accurately send the data to the target, TCP protocol adopts the three-way handshake strategy. After sending a packet using TCP protocol, TCP will not ignore the situation after the transmission, it will confirm to the other party whether the delivery was successful. The TCP flags SYN and ACK are used during the handshake. The sender first sends a packet with the SYN flag. After receiving the packet, the receiver sends back a packet with SYN/ACK flag to convey the acknowledgement. Finally, the sender sends back a packet with an ACK flag, indicating the end of the handshake. If the handshake is interrupted at some stage, the TCP protocol sends the same packets in the same order again.

What is your understanding of semantics?

2. It is conducive to SEO: establish good communication with search engines, and help crawlers to grab more effective information: crawlers rely on tags to determine the context and the weight of each keyword; 3, it is convenient for other devices to parse (such as screen readers, blind readers, mobile devices) to render web pages in a meaningful way; 4, easy to team development and maintenance, semantic more readable, is the next important trend of the web page, follow the W3C standard team to follow this standard, can reduce differentiation

29. How do you optimize your site’s files and resources?

Expected solutions include file merging file minimization/file compression using CDN managed cache use (multiple domain names to provide caching) and others

Name three ways to reduce page load times?

Compress CSS and JS files; merge JS and CSS files to reduce HTTP requests; 3. Place external JS and CSS files at the bottom; 4

What are the methods of js lazy loading?

As defer and async, create the DOM dynamically (create script, insert into the DOM, callBack after loading), and load js asynchronously on demand

What are your performance optimization methods?

(See Yahoo’s 14 Performance optimization rules for details). (1) reduce the number of HTTP requests: CSS Sprites, JS, CSS source compression, image size control appropriate; Web pages Gzip, CDN hosting, data cache, image server. (2) Front-end template JS+ data, reduce the bandwidth waste caused by HTML tags, front-end variables to save AJAX request results, each operation of local variables, no request, reduce the number of requests (3) using innerHTML instead of DOM operations, reduce the number of DOM operations, optimize javascript performance. (4) When there are many styles to set, set className instead of style. (5) Use less global variables and cache the search results of DOM nodes. Reduce IO read operations. (6) Avoid using CSS Expression, also known as Dynamic Properties. (7) Preload the image, put the stylesheet at the top and the script at the bottom with a timestamp.

33. Asynchronous loading and lazy loading

2. Get js code via Ajax and execute it via eval. 3. Create and insert an iframe that executes js asynchronously 5. Lazy loading: Some JS code is not needed immediately when the page is initialized, but is needed later in some cases.

What is the difference between GET and POST?

GET: Generally used to obtain information. The parameter is passed by URL and has a limit on the number of messages to be sent. The value is usually 2000 characters long. GET uses request. QueryString to GET the value of the variable, while POST uses Request.Form to GET the value. However, use POST requests in the following cases: POST is more stable and reliable than GET when sending user input containing unknown characters when it is not possible to send large amounts of data to the server using cached files (updating files or databases on the server) (POST has no data limit)

35. How do you manage your projects?

The advance team must determine the global style (Globe.css), encoding mode (UTF-8), etc. Writing habits must be consistent (e.g., inheritance, single style on one line); Annotate the style writer, each module is annotated in time (annotate the key style call place); Page annotations (for example, page module start and end); CSS and HTML folders are stored in parallel, with uniform names (such as style.css). JS sub folder name in accordance with the English translation of the JS function.

How can you optimize your code?

Code reuse avoids global variables (namespaces, closed Spaces, modular MVC…) Splitting functions prevents functions from being over-commented

37. What is FOUC (Unstyled Content Flicker)? How can you avoid FOUC?

<style type="text/ CSS "media="all">@import ".. /fouc.css"; </style>Copy the code

The @import reference to the CSS file is the culprit. IE will first load the whole HTML document OF the DOM, and then to import the external CSS file, therefore, in the page TO complete the DOM loading to complete the CSS import will have a period of time in the middle of the page content is not style, the length of this period of time with network speed, computer speed are related.

The solution is surprisingly simple, just add a <link> or <script> element between <head>.Copy the code

Understanding of website refactoring?

Site refactoring: Simplifying structure and adding readability without changing external behavior, while maintaining consistent behavior on the front end of the site. That means optimizing the site without changing the UI, and maintaining a consistent UI while extending it. For traditional websites refactoring is usually: Changing the table layout to DIV+CSS makes the front end compatible with modern browsers (for non-canonical CSS, such as the one that worked for IE6). Optimize for mobile Platforms Optimize for SEO. Deep site refactoring should be considered Write code strictly according to specifications, design extensible apis to replace old frameworks and languages (such as VB), enhance user experience. Generally speaking, optimization for speed is also included in refactoring. Compression of JS, CSS, image and other front-end resources (usually solved by the server). Using CDN to speed up resource loading for JS DOM optimization HTTP server file cache

What is elegant degradation and progressive enhancement?

Graceful degradation: Web sites work fine in all modern browsers, and if users are using older browsers, the code checks to make sure they work. Because of IE’s unique box-model layout problems, hacks for different versions of IE have been gracefully downgraded, adding candidates for browsers that don’t support functionality that degrade the experience in some way on older browsers without completely invalidate it. Incremental enhancement: Start with basic features supported by all browsers and gradually add features supported only by newer browsers, adding extra features to the page that do not harm the base browser

What is the difference between stack and queue?

Stack inserts and deletes are performed on one end, while queue operations are performed on both ends. Queue first in, first out, stack first in, last out. The stack allows inserts and deletes only at the end of the table, while the queue allows inserts at the end of the table and deletes only at the end of the table

What’s the difference between stack and heap?

Stack – automatically allocated and freed by the compiler to hold function parameter values, local variable values, etc. Heap – Usually allocated for release by the programmer, but may be reclaimed by the OS when the program ends if the programmer does not release it. Heap (data structure) : The heap can be thought of as a tree, such as heapsort; Stack: an advanced data structure.

What do you understand about the position of front-end interface engineer? What are its prospects?

The front end is the programmer closest to the user, closer than the back end, database, product manager, operations, security. With Node.js, the front-end can realize some things on the server. The front-end is the programmer closest to the user. The front-end is able to evolve the product from 90 points to 100 points or even better. Communication with team members, UI designers and product managers; Good page structure, page refactoring and user experience; Handle hacks, compatible, and write elegant code formats; Optimize for the server and embrace the latest front-end technology.

Code algorithms and stuff like that

43, array reindexof

var arr=[1.1.2.2.3.4.5.7.8.9.6.4.6.2,]
var arr2=[]
for(var i=0; i<arr.length; i++){if(arr2.indexOf(arr[i])<0){
        arr2.push(arr[i])
    }
}
console.log(arr2) 
Copy the code

44, ES6 method array deduplicate

let a = [1.5.6.3.8.0.5.7.0.4.2.7.5.4.5.9.22]
let b=new Set([...a])
console.log(b);
b=[...b];
console.log(b)
Copy the code

45. Bubble sort

var arr=[1.3.4.6.8.0.2.5.7.4.9.2];
var temp=0;
for (var i=0; i<arr.length; i++) {for(var j=0; j<arr.length-i; j++){if(arr[j]<arr[j+1]){
            temp=arr[j+1];
            arr[j+1]=arr[j]; arr[j]=temp; }}}console.log(arr)
Copy the code

46, Get the parameters in the URL

/ / test address: http://www.runobb.com/jqur/dfev.html?name=xiaohong&age=22
   function showWindowHref(){
        var sHref=window.location.href;
        var args=sHref.split('? ');
        if(args[1]==sHref){
            return ' ';
        }
        var aa=args[1].split('&');
        var obj={}
        for (var i=0; i<aa.length; i++) {var bb=aa[i].split('=')
            obj[bb[0]]=bb[1]}return obj;             
    }
Copy the code

47. Reduced dimensions of arrays

// Use [].concat.apply to realize dimension reduction
    var arr=[[1.2], [3.4]].function Jw(obj){
        console.log(Array.prototype.concat.apply([],obj))
            return Array.prototype.concat.apply([],obj);
    }
    Jw(arr);
// If the argument to concat is an element, that element is inserted directly into the new array; If the argument is an array, the elements of that array are inserted into the new array
    function reduceDimension(arr){
        let ret = [];
        for(let i=0; i<arr.length; i++){ ret=ret.concat(arr[i]) }console.log(ret)
        return ret;
    }
    reduceDimension(arr)  
/ / recursion
    function reduceDimension(arr){
        let ret = [];
        let toArr = function(arr){
            arr.forEach(function(item){
                item instanceof Array ? toArr(item) : ret.push(item);
            });
        }
        toArr(arr);
        console.log(ret)
        return ret;
    }
    reduceDimension([1.2[3.4[5.6]]])   
 //flat
     let list = [1.2.3[4[5]]];
     let res = list.flat(Infinity)
     console.log(res) // [1, 2, 3, 4, 5]
Copy the code

48, JS judge a string in the occurrence of the most number of characters, statistics the number of times

var str = 'asdfssaaasasasasaa';
var json = {};
for (var i = 0; i < str.length; i++) {
    if(! json[str.charAt(i)]){ json[str.charAt(i)] =1;
    }else{ json[str.charAt(i)]++; }};var iMax = 0;
var iIndex = ' ';
for(var i in json){
    if(json[i]>iMax){ iMax = json[i]; iIndex = i; }}console.log('The most frequent occurrences are :'+iIndex+'a'+iMax+'time');  // The most frequent occurrence is :a appears 9 times
Copy the code
let string = 'kapilalipak';
const table={}; 
for(let char of string) {
    table[char]=table[char]+1 || 1;
}
/ / output
console.log(table)// {k: 2, a: 3, p: 2, i: 2, l: 2}
Copy the code

49, write a function to clear the space before and after the string. (Compatible with all browsers)

function trim(str) {
    if (str & typeof str === "string") {
        return str.replace(/(^s*)|(s*)$/g.""); // Remove the front and back whitespace}}Copy the code

How to disable the forward/backward button in the browser with jquery

<script type="text/javascript" language="javascript">
$(document).ready(function() { 
     window.history.forward(1);
     //OR  
     window.history.forward(-1);  
});  
</script>
Copy the code

How do I get all the checkboxes in the page? (No third-party frameworks)

var inputs = document.getElementsByTagName("input");// Get all the input tag objects
var checkboxArray = [];// Initialize an empty array to hold the checkbox object.
for(var i=0; i<inputs.length; i++){var obj = inputs[i];
  if(obj.type=='checkbox'){ checkboxArray.push(obj); }}Copy the code

The method of catching exceptions in the program?

try{}catch(e){
  
}finally{}Copy the code

52, js sort

The ascending and descending sort function sortNumber

const arr1 = [6.1.2.3.4];
function sortNumber(a,b){
     return b-a;
}
arr1.sort(sortNumber);
console.log(arr1)
// [6, 4, 3, 2, 1]
Copy the code

Sorted by flag, with true displayed first

const arr2 = [
            { id: 10.flag: true },
            { id: 5.flag: false },
            { id: 6.flag: true },
            { id: 9.flag: false}];const r = arr2.sort((a, b) = > b.flag - a.flag);
console.log(r);
/ / /
// { id: 10, flag: true },
// { id: 6, flag: true },
// { id: 5, flag: false },
// { id: 9, flag: false }
// ]
Copy the code

If you like it, please give it a thumbs-up. If you feel helpful to the people around you, please move your finger and share it. Thank you for taking the time to read it, and thank you for your likes and shares.

Other Popular articles

  1. Es6 related summary
  2. JS array reduce() method
  3. Js array sort() method
  4. Set the token to the request header
  5. Es6 extension operator three points (…)

More will follow

  1. HTML Interview Summary
  2. CSS Interview Summary
  3. Vue interview summary
  4. Small program interview summary

Finally, it will be put together