[gold, silver and silver] summary of common questions in Js interview

Summarize some knowledge of front-end js, sort out the notes and share with you. Some knowledge will often be asked during the front-end interview, so make a record and hope to be helpful to you. If you have any questions, you can point out and actively correct them.
If you like, you can like or leave a message. I will continue to update the interview questions ~, thank you~~~

Question 1. What is the difference between pre + +, post + +?

var i=2 ;
a = i++ //Assign the value of i to a, that is, a = i, and then execute i = i + 1; two
a = ++i //Assign the value of i+1 to a, that is, a = i+1, and then execute I = i+1; three


The first + + is self addition before calculation, and the second + + is self addition before calculation

1: Pre + + is to assign the value after + 1 to the variable and add 1 to itself at the same time;

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

What data types does JS have?

Js common data type undefined null Boolean number string
Js reference type object array function
ES6 basic data type has more than one symbolo

js judgment type?

null and array cannot be detected, and the result is object, so typeof is often used to detect basic types
number, boolean, string, undefined, null and symbol types cannot be detected, so instancof is often used to detect complex types and hierarchical relationships
Null and undefined have no constructor method, so the constructor cannot judge undefined and null. But the direction of the contractor can be changed, so it is not safe
All types can be judged

How to detect data types

 Example: console.log(typeof true) // boolean

 Example: console.log([1,2] instanceof Array) // true

 Example: console.log([1, 2].constructor === Array) // ture

 Example: Object.prototype.toString.call([1, 2]) // [object Array]

Method of Js array

Convert join() array to string
push() tail add
pop() tail deletion
shift() header deletion
unshift() header add
sort() sort
concat() links two or more arrays
  var arr=[1,2,3,4,5]
  console.log(arr.slice(1)) //[2,3,4,5] select a new array composed of all elements with serial number from 1 to the last
  console.log(arr.slice(1,3)) //[2,3] does not contain elements with serial number and serial number of 3
index parameter: must be an integer to specify the position to be added or deleted. Use a negative number to specify the position from the end of the array
howmany parameter: must be the quantity to be deleted. If it is 0, the item will not be deleted
  item1,...itemx parameter: optional, a new item added to the array
  var arr=[1,2,3,4,5]
  console.log(arr.splice(2,1,"hello"));//[3] New array returned
indexOf() and lastIndexOf() (new in ES5)
forEach() (new in ES5)
map() (new in ES5)
filter() (newly added in ES5)
every() (ES5 added)
some() (new in ES5)
reduce() and reducereight() (new in ES5)

Array. In JS Splice() and array What's the difference between slice () methods?

Without much to say, let's take a look at the first example:

var arr=[0,1,2,3,4,5,6,7,8,9];//Set an array
//Therefore, we simply infer the meaning of the two function parameters of quantity,
slice(start,end)The first parameter indicates the start position,The second represents the intercepted location(This location is not included)
splice(start,length)Start position of the first parameter,The second parameter is the intercept length

Then look at the second:

var x=y=[0,1,2,3,4,5,6,7,8,9]
console.log(x);[0,1,2,3,4,5,6,7,8,9]The original array has not changed
//Next, test splice in the same way
console.log(y);//The values of [1,9,9] in the original array are eliminated

Although slice and slice intercept array objects, there are still obvious differences between them. In the function parameters, the first parameter of slice and slice is the interception start position, the second parameter of slice is the interception end position (excluding), and the second parameter of slice (indicating the length intercepted from the start position). Slice will not change the original array, but slice will directly eliminate the intercepted data in the original array!

slice will not change the original array, and splice will change the original array

Numerical conversion

JSON.parse() to json object
JSON.stringify() to json string
String(),toString() to string type
Number parseInt() string to numeric type
split string to array
join array to string

What is cross domain, common cross domain

Since the browser follows the homologous strategy to obtain data, when accessing non homologous resources, it needs to cross domain. The common cross domain methods are jsonp, a img src cors
Homology policy: the security policy of the same protocol, port and domain name
jsonp principle
Dynamically create a script tag and use the callback function to get the value

function callbackFunction(){
  alert("RollBACK ");
var script=document.createElement("script");

Principle of CORS:
When the amount of data transmitted is large and the form of get is uncertain, CORS cross domain can be used. The principle of CORS is to define a cross domain access mechanism, which can enable ajax to achieve cross domain access. CORS allows web applications in one domain to submit cross domain ajax requests to another domain. This function is very simple, just send a response header by the server.
Jsonp is in the form of get and carries a limited amount of information, so cors is the best choice when the amount of information is large.

http protocol:

http protocol defines the communication mode of file transfer between server and client
Request resources on the server, request html css js picture files, etc
There are many kinds of request methods (all methods are capitalized). The explanation of each method is as follows:
get (get) request to get the resource identified by the request URI -- get the resource
post (post) attaches new data to the resource identified by the request URI - transmission resource
head (head) request to obtain the response message header of the resource identified by the request URI --- obtain the header of the message
put (put) requests the server to store a resource and use the request URI as its identification - update the resource
delete (delete) requests the server to delete the resource identified by the request URI --- delete the resource
trace (trace) requests the server to send back the received request information, which is mainly used for testing or diagnosis
Connect (connect) reserved for future use
Options (options) requests to query the performance of the server or the options and requirements related to resources
Common status codes:
200 request succeeded
301 resources (web pages, etc.) are permanently transferred to other URLs
404 the requested resource does not exist
500 internal server error

HTTP status code

100 continue. Generally, when sending a post request, after the http header has been sent, the server will return this information to confirm, and then send the specific parameter information
OK message returns to 200
201 the created request succeeded and the server created a new resource
202 the accepted server has accepted the request but has not yet processed it
301 the page requested by moved permanently has been permanently moved to a new location.
302 Found temporary redirection.
303 See Other temporarily redirects and always uses GET to request new URI s.
304 not modified the requested web page has not been modified since the last request.
The 400 Bad Request server cannot understand the format of the request, and the client should not try to initiate the request with the same content again.
401 Unauthorized request not authorized.
403 Forbidden access is prohibited.
404 Not Found cannot find a resource that matches the URI.
500 Internal Server Error is the most common server-side error.
503 Service Unavailable the server cannot process the request temporarily (it may be overloaded or maintained).

Tell me about your understanding of closures

Closures are mainly used to design private methods and variables. The advantage of closures is that they can avoid the pollution of global variables. The disadvantage is that closures will reside in memory and increase memory usage. Improper use can easily lead to memory leakage.
Closures have three characteristics:

    1.Function nested function
    2.Internal functions can reference external parameters and variables
    3.Parameters and variables are not recycled by the garbage collection mechanism

Closure purpose
1 cache
Imagine that we have a function object whose processing process is very time-consuming. Each call will take a long time, so we need to store the calculated value. When calling this function, first look it up in the cache. If it cannot be found, calculate it, and then update the cache and return the value. If it is found, directly return the found value. Closure can do this because it does not release external references, so that the values inside the function can be retained.
2 realize packaging
Let's take a look at an example of encapsulation. You can't access its internal variables outside person, but by providing closures:

var person = function(){    
    //Variable scope is internal to the function and cannot be accessed externally    
    var name = "default";              
    return {    
       getName : function(){    
           return name;    
       setName : function(newName){    
           name = newName;    
print(person.name);//Direct access, the result is undefined    

How to prevent event bubbling?

Ie: stop bubbling ev cancelBubble = true; Non ie ev stopPropagation();

How do I block default events?

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

Event agent

Event agent refers to binding an event to the parent box, and then the child box triggers the event. Due to the event bubble, the parent box event is also triggered. At this time, in the time processing function of the parent box, you can obtain the target time through srclelement or target attribute and process it accordingly

Add, delete or replace the method of inserting into a node?

1)Create a new node
createElement() //Create a concrete element
createTextNode() //Create a text node
2)Add, remove, replace, insert
appendChild() //add to
removeChild() //remove
replaceChild() //replace
insertBefore() //insert
getElementsByTagName() //By label name
getElementsByName() //Pass the value of the Name attribute of the element
getElementById() //Uniqueness through element Id

What is the difference between document load and document ready?

document.onload executes js only after the structure and style, external js and pictures are loaded
document.ready is a method that executes after the dom tree is created. The native species do not have this method. There is $() in jquery ready(function)

What are the event flow models of Javascript?

"Event capture": from top to bottom, window, document, document document,body Target element

"Event bubbling": from bottom to top: vice versa

"DOM event flow": three stages: event capture, target stage and event bubbling

Dom event class:

Dom0  element.onclick=function(){}

DOM2 element.addEventlistener('click',function(){},flase)

DOM3 element.addEventlistener('keyup',function(){},flase)

Event.preventdefault()  Block default events

Event.stoppropagation()  Stop bubbling

Event.currenTtarget()Event agent 

Event.target Currently clicked element

What is the difference between null and undefined?

null is an object representing "None", which is 0 when converted to a value; undefined is an original value indicating "None", which is NaN when converted to a numerical value.

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 exist. It is often used to indicate that a function attempts to return an object that does not exist.

call() and What are the differences and functions of apply()?

The same point: the two methods have exactly the same effect and change the direction of this

Differences: the parameters passed by the method are different



Apply() receives two parameters, one is the scope of the function and the other is the parameter array.

The first parameter of the Call() method is the same as apply (), but the parameters passed must be enumerated.

Principles of mvc and mvvm modes:

Why does JS distinguish between micro tasks and macro tasks?

(1) js is single threaded, but it is divided into synchronous and asynchronous
(2) Both micro task and macro task are asynchronous tasks, which belong to a queue
(3) Macro tasks are generally script, setTimeout, setInterval and setImmediate
(4) Micro task: native Promise
(5) In case of micro task, execute the micro task first. After execution, if there is no micro task, execute the next macro task. If there are micro tasks, execute the micro tasks one by one in order

setTimeout and setInterval

//setTimeout is executed in 3 seconds

//setInterval is executed every three seconds and repeated continuously
//Both executions are asynchronous

Deep copy shallow copy

The fundamental difference between deep copy and shallow copy is whether to really obtain the copied entity of an object rather than a reference.

Suppose B copies A. when modifying a, check whether B changes:

If B also changes, it means that it is a shallow copy, and the hand is short! (modify the same value in heap memory)

If B doesn't change, it means it's a deep copy and self-supporting! (modify different values in heap memory)
Shallow copy implementation:

  var a = [1, 2, 3, 4, 5];
  var b = a;
  a[0] = 2
  console.log(b);//[2,2,3,4,5] / / B will change with the change of a

Deep copy implementation:

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

Rearrange redraw

Reflux (rearrangement):
When some (or all) of the render tree needs to be rebuilt due to changes in the size, layout and hiding of the elements. This is called reflow. Each page needs to reflow at least once, that is, when the page is loaded for the first time, reflow is bound to occur at this time, because it is necessary to build render tree. During reflow, the browser will invalidate the affected part of the rendering tree and reconstruct this part of the rendering tree. After reflow is completed, the browser will redraw the affected part to the screen, which is called redrawing.
When some elements in render tree need to update attributes, these attributes only affect the appearance and style of the elements, but will not affect the layout, such as background color. It is called redrawing.
Reflow will cause redrawing, but redrawing does not necessarily cause reflow. For example: only when the color changes, it will only redraw without causing backflow
Reflow is required when page layout and geometric properties change
For example: add or delete visible DOM elements, change the position of elements, change the size of elements - margin, filling, border, width and height, and change the content.

Anti shake and throttling?

In the process of front-end development, we often need to bind some continuously triggered events, such as resize, scroll, mousemove keyup, etc., but sometimes we don't want to execute functions so frequently in the process of continuously triggering events.

How do we usually solve this problem? Generally speaking, anti shake and throttling are better solutions.
1. Anti shake:
It refers to the function execution after n seconds after the event is triggered. If the event is triggered again within n seconds, the function execution time will be recalculated. Application scenario (applicable to the case where multiple events respond only once): add an anti shake function to the button to prevent the form from being submitted multiple times; Judge whether the scroll slides to the bottom; For continuous input in the input box for AJAX verification, using function anti shake can effectively reduce the number of requests.
Here's a scenario: listen to an input box and trigger the change event after the text changes. If the keyup event is used directly, the change event will be triggered frequently. After anti shake is added, the change event will be triggered when the user input ends or pauses.
The so-called anti shake means that the function can only be executed once in n seconds after the event is triggered. If the event is triggered again in n seconds, the function execution time will be recalculated.

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <input type="text" id="input1">
    const input1 = document.getElementById('input1')
//1. Without anti shake, the change event will be triggered all the time
    input1.addEventListener('keyup', function(){

//2. Simple implementation of anti shake
    let timer = null
    input1.addEventListener('keyup', function(){
        timer = setTimeout(() => {
            //Simulate trigger change event
            //Clear timer
            timer = null
        }, 1000)

//3. Encapsulate the anti shake function as a tool
    function debounce(fn, delay = 50){
        //timer is in a closure and cannot be modified by others
        let timer = null
        return function(){
            timer = setTimeout(() => {
                fn.apply(this, arguments)
                timer = null
            }, delay)
    input1.addEventListener('keyup', debounce(function(){ 
    }, 600))

Then the anti shake function after packaging is:

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

2. Throttling:
Continuously sent events execute the function only once in n seconds. Application scenario (suitable for evenly distributing and triggering a large number of events according to time): DOM element dragging; Canvas brush function.
Now let's give a scenario: drag an element and get the dragged position of the element at any time. If the drag event is used directly, it will be triggered frequently, which can easily lead to jamming. After throttling is added, no matter how fast the drag speed is, it will be triggered every fixed time.
Throttling means that events are triggered continuously, but the function is executed only once in n seconds. Throttling dilutes how often the function is executed.

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
            border: 1px solid #ccc;
            width: 200px;
            height: 100px;
    <div id = "div1" draggable="true">draggable </div>
        const div1 = document.getElementById('div1')
  //1. Simple throttling
        let timer = null
        div1.addEventListener('drag', function(e){
            timer = setTimeout(() => {
                console.log(e.offsetX, e.offsetY)
                timer = null //The timer is null only after the timer is executed
            }, 1000)            

  //2. Encapsulate the throttling function as a tool
        function throttle(fn, delay = 100){
            let timer = null
            return function(){ 
                timer = setTimeout(() => {
                    fn.apply(this, arguments)
                    timer = null
        div1.addEventListener('drag', throttle(function(e){ //The formal parameter e will be passed to the function returned after the throttle function runs
                console.log(e.offsetX, e.offsetY)   

Then the encapsulated throttling function is:

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

What happens to a page from entering the URL to the completion of page loading and display?

There are four steps:
(1) , when sending a URL request, whether the URL is the URL of the Web page or the URL of each resource on the Web page, the browser will open 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 TCP three handshake negotiation. The handshake includes a synchronization message, a synchronization response message and a response message, which are transmitted between the browser and the server. The handshake first attempts to establish communication by the client, then the server answers and accepts the request of the client, and finally the client sends the message that the request has been accepted.
(3) , once the TCP/IP connection is established, the browser will send an HTTP GET request to the remote server through the connection. The remote server finds the resource and returns it with an HTTP response. An HTTP response status of 200 indicates a correct response.
(4) At this point, the Web server provides resource services and the client starts downloading resources.
After the request is returned, it enters the front-end module we focus on
In short, the browser will parse HTML to generate DOM Tree, then generate CSS Rule Tree according to CSS, and javascript can operate DOM according to DOM API
Details: what happened in the process from entering the URL to receiving it by the browser?

Talk about the triple handshake strategy of TCP transmission

In order to deliver the data to the target accurately, TCP protocol adopts the strategy of three handshakes. After sending the data packet with TCP protocol, TCP will not ignore the situation after transmission. It will confirm whether it has been successfully delivered to the other party. In the handshake process, TCP flags are used: SYN and ACK.
The sender first sends a data packet with SYN flag to the other party. After receiving, the receiving end returns a data packet with SYN/ACK flag to convey the confirmation information. Finally, the sender sends back a packet with ACK flag, representing the end of "handshake"
If the handshake is interrupted inexplicably at a certain stage, the TCP protocol will send the same packets in the same order again.

What's your understanding of semantic?

1. When the style is removed or lost, the page can show a clear structure
2. Conducive to SEO: establish good communication with search engines and help crawlers capture more effective information: crawlers rely on tags to determine the context and the weight of each keyword;
3. Facilitate the analysis of other devices (such as screen reader, blind reader and mobile device) to render web pages in a meaningful way;
4. It is easy for the team to develop and maintain, semantic and more readable, which is an important trend of the web page in the next step. Teams that follow the W3C standard follow this standard, which can reduce differentiation

How do you optimize the files and resources of the website?

Expected solutions include:
File merge
File minimization / file compression
Using CDN hosting
Use of cache (multiple domain names to provide cache)

Please name three ways to reduce page loading time?

1. Compress css and js files
2. Merge js and css files to reduce http requests
3. External js and css files are placed at the bottom
4. Reduce dom operations and replace unnecessary dom operations with variables as much as possible

What are the ways to delay the loading of js?

defer and async, dynamic DOM creation (script is created, inserted into the DOM, and called back after loading), and asynchronous loading of js on demand

What performance optimization methods do you have?

(see Yahoo's 14 performance optimization principles for details).
(1) Reduce the number of http requests: CSS Sprites, JS, CSS source code compression and appropriate image size control; Web page Gzip, CDN hosting, data cache, image server.
(2) The front-end template JS + data reduces the waste of bandwidth caused by HTML tags. The front-end uses variables to save AJAX request results. Each time the local variables are operated, there is no need to request and reduce the number of requests
(3) Use innerHTML instead of DOM operations to reduce the number of DOM operations and optimize the performance of javascript.
(4) When there are many styles to set, set className instead of directly operating style.
(5) Use less global variables and cache the results of DOM node lookup. Reduce IO read operations.
(6) Avoid using CSS Expression, also known as dynamic properties.
(7) Preload the picture, put the style sheet at the top, put the script at the bottom and time stamp it.

Asynchronous loading and deferred loading

1. Asynchronous loading scheme: insert script tag dynamically
2. Get js code through ajax and execute it through eval
3. Add the defer or async attribute on the script tag
4. Create and insert iframe and let it execute js asynchronously
5. Delayed loading: some js code is not needed immediately when the page is initialized, but only in some cases later.

The difference between GET and POST, when to use POST?

GET: it is generally used for information acquisition. The URL is used to pass parameters. There is also a limit on the number of messages sent, which is generally 2000 characters
POST: it is generally used to modify the resources on the server. There is no limit on the information sent.
The get method requires request Querystring to get the value of the variable, and post through request Form to get the value of the variable, that is, get passes the value through the address bar, while post passes the value through submitting the form.
However, use POST requests when:
Cannot use cache file (update file or database on server)
Send a large amount of data to the server (POST has no limit on the amount of data)
When sending user input containing unknown characters, POST is more stable and reliable than GET

How do you manage your project?

The advance team must determine the global style (globe.css), coding mode (utf-8), etc;
Written in the same style (for example, the list must be written in the same style);
The annotation style writer shall mark all modules in time (mark the place where the key style is called);
Mark the page (such as the beginning and end of the page module);
CSS and HTML are stored in parallel folders, and the names must be unified (for example, style.css);
JS is stored in folders and named according to the English translation of the JS function.

How do you optimize your code?

code reuse
Avoid global variables (namespace, enclosed space, modular mvc...)
Split functions to avoid overstaffing

What is FOUC (no style content flashing)? How do you avoid FOUC?  

FOUC - Flash Of Unstyled Content Document style flashing
<style type="text/css" media="all">@import "../fouc.css";</style>

The @ import that references CSS files is the culprit of this problem. IE will first load the dom of the entire HTML document, and then import the external CSS file. Therefore, there will be a period of time between the completion of page DOM loading and the completion of CSS import. The content on the page has no style. The length of this period of time is related to the Internet speed and computer speed.
The solution is surprisingly simple. Just add a < link > or < script > element between < head >.

Understanding of website reconstruction?

Website reconstruction: the behavior of simplifying the structure and adding readability without changing the external behavior, while maintaining consistency at the front end of the website. In other words, optimize the website without changing the UI, and maintain a consistent UI while expanding.
For traditional websites, refactoring is usually:
Change the table layout to DIV+CSS
Make the front end of the website compatible with modern browsers (for non-standard CSS, such as effective for IE6)
Optimization of mobile platform
Optimize for SEO
Aspects that should be considered in deep-seated website reconstruction
Reduce coupling between codes
Keep your code flexible
Write code in strict accordance with the specifications
Design extensible API
Replace the old framework and language (such as VB)
Enhance user experience
Generally speaking, the optimization of speed is also included in refactoring
Compress front-end resources such as JS, CSS and image (usually solved by the server)
Program performance optimization (such as data reading and writing)
Using CDN to speed up resource loading
Optimization of JS DOM
File cache for HTTP server

What is graceful degradation and progressive enhancement?

Elegant degradation: Web sites work well in all new browsers, and if users use older browsers, the code checks to see if they work properly. Due to the unique box model layout of IE, hack practice for different versions of IE has been gracefully downgraded. Add candidate schemes for browsers that cannot support functions, so that they can experience some form of degradation on old browsers without complete failure
Progressive enhancement: start with the basic functions supported by all browsers, gradually add those functions only supported by new browsers, and add additional features harmless to the basic browser to the page

What is the difference between stack and queue?

The insertion and deletion operations of the stack are carried out at one end, while the operation of the queue is carried out at both ends.
Queue FIFO, stack FIFO.
The stack only allows insertion and deletion at the end of the table, while the queue only allows insertion at the end of the table and deletion at the head

What is the difference between stack and heap?

stack - automatically allocated and released by the compiler to store the parameter values of functions and the values of local variables.
heap - generally allocated and released by the programmer. If the programmer does not release it, it may be recycled by the OS at the end of the program.
Heap (data structure): heap can be regarded as a tree, such as heap sorting;
Stack (data structure): a first in and last out data structure.

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

The front end is the programmer closest to the user, which is closer to the back end, database, product manager, operation and security.

1,Realize interface interaction
2,Improve user experience
3,Yes Node.js,The front end can realize some things on the server side

The front end is the programmer closest to the user. The ability of the front end is to make the product evolve from 90 points to 100 points, or even better,
Participate in the project and complete the effect drawing quickly and high quality, accurate to 1px;
Communicate with team members, UI design and product manager;
Good page structure, page reconstruction and user experience;
Handle hack, compatible and write beautiful code format;
Optimize the server and embrace the latest front-end technology.

Tell me about some of the most popular things recently? Which websites do you often visit?

Node.js,Mongodb,npm,MVVM,MEAN,three.js,React .
Websites: w3cfuns,sf,hacknews,CSDN, Muke, blog Garden, InfoQ,w3cplus, etc

Code algorithm and so on

Array de duplication indexOf

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++){

es6 method array de duplication

let a = [1,5,6,3,8,0,5,7,0,4,2,7,5,4,5,9,22]
let b=new Set([...a])

Bubble sorting

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++){

Get parameters in 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('?');
            return '';
        var aa=args[1].split('&');
        var obj={}
        for (var i=0;i<aa.length;i++) {
            var bb=aa[i].split('=')
        return obj;             

Dimensionality reduction array

//Use [] concat.apply to reduce dimension  
    var arr=[[1,2],[3,4]];
    function Jw(obj){
            return Array.prototype.concat.apply([],obj);
//If the parameter of concat method is an element, the element will be directly inserted into the new array; If the parameter is an array, the elements of the array will be inserted into the new array
    function reduceDimension(arr){
        let ret = [];
        for(let i=0;i<arr.length;i++){
        return ret;
    function reduceDimension(arr){
        let ret = [];
        let toArr = function(arr){
                item instanceof Array ? toArr(item) : ret.push(item);
        return ret;
    reduceDimension([1, 2, [3, 4, [5, 6]]])   
    let list = [1, 2, 3, [4, [5]]];
    let res = list.flat(Infinity)
    console.log(res) // [1, 2, 3, 4, 5]    

js determines the character that appears the most times in a string and counts the number

var str = 'asdfssaaasasasasaa';
var json = {};
for (var i = 0; i < str.length; i++) {
       json[str.charAt(i)] = 1;
var iMax = 0;
var iIndex = '';
for(var i in json){
         iMax = json[i];
         iIndex = i;
console.log('The most frequent occurrence is:'+iIndex+'appear'+iMax+'second');  //The most frequent occurrence is: a appears 9 times
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}

Write a function to clear the spaces before and after the string. (compatible with all browsers)

function trim(str) {
    if (str & typeof str === "string") {
        return str.replace(/(^s*)|(s*)$/g,""); //Remove white space before and after

How to disable the forward and backward buttons of the browser with jquery?

<script type="text/javascript" language="javascript">
$(document).ready(function() { 

How to get all the checkbox es in the page? (no third-party framework)

var inputs = document.getElementsByTagName("input");//Get all input tag objects
var checkboxArray = [];//Initialize an empty array to store the checkbox object.
for(var i=0;i<inputs.length;i++){
  var obj = inputs[i];

How to catch exceptions in the program?


js sort

Ascending Descending sorting function sortNumber

const arr1 = [6,1,2,3,4];
function sortNumber(a,b){
     return b-a;
// [6, 4, 3, 2, 1]

Sort by flag, and those that are true are displayed in the front

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);
// [
//     { id: 10, flag: true },
//     { id: 6, flag: true },
//     { id: 5, flag: false },
//     { id: 9, flag: false }
// ]

This article participated in the essay solicitation of SegmentFault "How to" kill "an interviewer?" , you who are reading are welcome to join us.

Tags: Javascript Front-end Interview

Posted by curtm on Wed, 30 Mar 2022 09:48:10 +0300