JS interview related questions

Time:2022-1-3

catalogue

  1. closure

  2. Class inheritance and creation

  3. How to solve callback hell

  4. Event delegation

  5. Let’s talk about lazy loading and preloading of pictures

  6. The difference between mouseover and mouseenter

  7. What does the new operator of JS do

  8. Change the pointing function of this pointer inside the function (the difference between bind, apply and call)

  9. JS, such as clientheight, scrollheight, offsetHeight, and the difference between scrolltop, offsettop, and clientop?

  10. Five ways to load JS asynchronously

  11. JS throttling and anti chattering

  12. JS garbage collection mechanism

  13. Commonjs, AMD and CMD

  14. Shallow copy and deep copy

  15. Encapsulate native Ajax into promise

  16. Achieve two columns of equal height

  17. Execution order of code

  18. How to achieve sleep effect

  19. JS judge data type

  20. JS array common methods

  21. Array de duplication

  22. performance optimization

  23. Language features of JS

  24. Determine whether the variable is of array type

  25. Function coritization

  26. Can the arrow function new

  27. Execute function now

  28. JS function overload

  29. fetch

  30. RESTful

31. Underlying principles of echarts

  1. WebSocket

1. Closure

A closure is a function that has access to a variable in the scope of another function;

function aaa(){
  var name = "xxx"
  return function bbb(){
    alert(name);
  }
}

Common timer problems

for( var i = 0; i < 5; i++ ) {
    setTimeout(() => {
        console.log( i );
    }, 1000)
}

The setTimeout function is executed at the end of the current execution queue. The obtained I is I = 5 of the outermost scope, so five 5 are obtained

So what if you want to get 0-4 after 1s? Create a closure within a for loop

for (var i = 0; i < 5; i++) {
    (function(j) {
        setTimeout(function() {
            console.log(j);
        },1000)
    })(i)
}

Similarly, setTimeout is executed at the end of the execution queue. The obtained J is the J of the external function. Since the variables in the closure will be saved, the obtained J each time is 0,1,2,3,4 respectively

Because closures will reside in memory, improper use will lead to memory overflow

2. inherit

3. How to solve the problem

1. Disassembly function: disassemble each step into a single function

function buildCatList(list, returnVal, fn) {
    setTimeout(function (name) {
        var catList = list === '' ? name : list + ',' + name
        fn(catList)
    }, 200, returnVal)
}
buildCatList('', 'Panther', getJanguar)
function getJanguar(list) {
    buildCatList(list, 'Janguar', getLynx)
}
function getLynx(list) {
     buildCatList(list, 'Lion', print)
}
function print(list) {
    console.log(list)
}
// Panther,Janguar,Lion

2. Event publishing / listening mode
On the one hand, it listens to an event and performs corresponding callback operations when an event occurs; On the other hand, when some operations are completed, the callback is triggered by publishing events, so that the originally bundled code can be decoupled.
3. Through promise chain call

function buildCatList(list, returnVal) {
    return new Promise(function (resolve, reject) {
        setTimeout(function (name) {
            var catList = list === '' ? name : list + ',' + name
            resolve(catList)
        }, 200, returnVal)
    })
}
buildCatList('', 'Panther').then(function (res) {
    return buildCatList(res, 'Janguar')
}).then(function (res) {
    return buildCatList(res, 'Lion')
}).then(function (res) {
    console.log(res)
})
// Panther,Janguar,Lion

Although promise function has changed the previous writing method of callback hell, it is still a function suite function, which doesn’t look so beautiful
4. Effect method of suspending execution through generator function

function getPanther(list) {
    return list + 'Panther' + ','
}
function getJaguar(list) {
    return list + 'Jaguar' + ','
}
function getLion(list) {
    return list + 'Lion'
}
function* buildCatList() {
    yield getPanther
    yield getJaguar
    yield getLion
}
//Process control
function run(fn){
    Const Gen = fn() // call the generator function and return an iterator object
    var a = gen.next(). Value ('') // call the next () method of the ergodic object, and an object with value and done attributes will be returned
    var b = gen.next().value(a)
    var c = gen.next().value(b)
    console.log(c)
}
Run (buildcatlist) // start execution
// Panther,Jaguar,Lion

Although generator can provide better syntax structure, it is not appropriate to use the context of generator and yield here
5. Async / await through the asynchronous function of es8

  • Async means that this is an async function, and await can only be used in this function
  • Await means to wait here for the promise to return the result before continuing execution
  • Await should be followed by a promise object (of course, other return values do not matter, but will be executed immediately)
  • Await waits for a promise object, but it does not have to write Then (), you can get the return value directly
function buildCatList(list, returnVal) {
    return new Promise(function (resolve, reject) {
        setTimeout(function (name) {
            var catList = list === '' ? name : list + ',' + name
            resolve(catList)
        }, 200, returnVal)
    })
}
function fn(list) {
    return list + ',' + 555
}
async function render() {
    var a = await buildCatList('','Panther')
    var b = await buildCatList(a, 'Jaguar')
    var c = await buildCatList(b, 'Lion')
    var d = await fn(c)
    console.log(d)
}
render()
// Panther,Jaguar,Lion,555

The code is concise and clear, and asynchronous code also has the structure of “synchronous” code

4. Event delegation

brief introduction: event delegation means that the listening function is not set on the place where the event occurs (direct DOM), but on its parent element. Through event bubbling, the parent element can listen to the triggering of events on the child element, and make different responses by judging the type of Dom of the event occurrence element.

give an example: the most classic is the event listening of UL and Li tags. For example, when adding an event, we use the event delegation mechanism. Instead of adding it directly on the Li tag, we add it on the UL parent element.

benefit: it is more suitable for binding dynamic elements. The newly added child elements can also have listening functions or event triggering mechanisms.

5. Talk about lazy loading and preloading of pictures

Preload: load pictures in advance. When users need to view them, they can render them directly from the local cache.
Lazy loading: the main purpose of lazy loading is to optimize the front end of the server and reduce the number of requests or delayed requests.

The essence of the two technologies: the behavior of the two is opposite, one is to load in advance, and the other is to load slowly or even not.
Lazy loading can relieve the pressure on the front end of the server, while preloading will increase the pressure on the front end of the server.

6. The difference between mouseover and mouseenter

mouseover: when the mouse moves into an element or its child elements, events will be triggered, so there is a repeated triggering and bubbling process. The corresponding removal event is mouseout
mouseenter: when the mouse removes the element itself (excluding the child elements of the element), it will trigger an event, that is, it will not bubble. The corresponding removal event is mouseleave

7. What does the new operator of JS do

New has gone through four stages
1. Create an empty object

var obj = new Object();

2. Set the prototype chain (after calling the constructor to create a new instance, the interior of the instance will contain a pointer (internal attribute) to the prototype object of the constructor)

obj.__proto__= Func.prototype;

3. Point this in func to obj and execute func’s function body. (after creating a new object, assign the scope of the constructor to the new object (so this points to the new object)

var result =Func.call(obj);

4. Determine the return value type of func:

If it is a value type, obj is returned. If it is a reference type, an object of this reference type is returned

if (typeof(result) == "object"){
  func=result;
}
else{
    func=obj;;
}

By default, the return value of the function is undefined, that is, if the defined return value is not displayed, except for the constructor. The new constructor returns the newly created object by default without return.

However, when the return value is displayed, if the return value is the basic data type {string, number, null, undefined, Boolean}, the return value is still the newly created object.

The return value of the function is the specified object only when the display returns a non basic data type. In this case, the value referenced by this is discarded

8. Change the pointing function of this pointer inside the function (the difference between bind, apply and call)

Usage of call()

var obj = {
    Text: 'my two hobbies are:'
}

function getHobby(a, b) {
    console. Log (this. Text + A + 'and' + b)
}

getHobby. Call (obj, 'football', 'badminton')
//My two hobbies are football and badminton

Usage of apply()

var obj = {
    Text: 'my two hobbies are:'
}

function getHobby(a, b) {
    console. Log (this. Text + A + 'and' + b)
}

getHobby. Apply (obj, ['football', 'badminton'])
//My two hobbies are football and badminton

Usage of bind()

var obj = {
    Text: 'my two hobbies are:'
}

function getHobby(a, b) {
    console. Log (this. Text + A + 'and' + b)
}

getHobby. Bind (obj, 'football', 'badminton') ()
//My two hobbies are football and badminton

1. The first parameter of the three is the direction of this.

  1. Call and bind pass in a parameter list after the first parameter. The second parameter of apply is the parameter array.
  2. Call and apply are immediate calls. Bind returns the corresponding function, which needs to be called ().

9. What are the differences between various positions of JS, such as clientheight, scrollheight, offsetHeight, and scrolltop, offsettop, and clientop?

Clientheight: indicates the height of the visible area, excluding border and scroll bar
OffsetHeight: indicates the height of the visible area, including border and scroll bar

Scrollheight: indicates the height of all areas, including the parts hidden due to scrolling.

ClientTOP: indicates the thickness of the border. If it is not specified, it is generally 0

Scrolltop: the height hidden after scrolling. It gets the height of the object from the top relative to the parent coordinate (CSS positioned element or body element) specified by the offsetparent attribute.

10. Five ways to load JS asynchronously

1. Async = “async” attribute of < script > tag
The new attributes in HTML5 are supported by chrome, FF, IE9 & IE9 + (not supported by IE6 ~ 8). In addition, this approach does not guarantee that scripts are executed sequentially.
2. Defer = “defer” attribute of < script > tag
Compatible with all browsers. In addition, this method ensures that all scripts that set the defer attribute are executed sequentially.
3. Dynamically create < script > tags

(function(){
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = "http://code.jquery.com/jquery-1.7.2.min.js";
    var tmp = document.getElementsByTagName('script')[0];
    tmp.parentNode.insertBefore(script, tmp);
})();

11. JS throttling and anti shake

<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>
    html,
    body {
        height: 500%;
    }
</style>
 
<body>
    < button id ='btn '> Click < / button >
    <script>
        //Throttling: after a function is executed, it will be executed for the second time only after it is greater than the set execution cycle,
        //There is a function that requires frequent departure. For performance optimization, only the first departure takes effect within the specified time, and the later ones do not take effect
        /*FN the throttled function Deley specifies the time*/
        function throttle(fn, delay) {
            //Record the last function departure time
            let lastTime = 0
            return function() {
                //Record the touch time of the current function
                let nowTime = Date.now()
                if (nowTime - lastTime > delay) {
                    fn.call(this)
                    lastTime = nowTime
                }
            }
        }
        document.onscroll = throttle(() => {
            console. Log ('trigger succeeded! '+ date. Now())
        }, 1000)
 
        //------------------------------------------------------------------------------------------------------------------------
        //Anti shake function: a function that starts frequently. It only takes effect for the last time within a specified time, and the previous one does not take effect. For example, click the button frequently
        function debounce(fn, delay) {
            let timer = null
            return function() {
                //Clear the last time delay
                clearTimeout(timer)
                    //Reset the new delay,
                timer = setTimeout(() => {
                    fn.call(this)
                }, delay)
            }
        }
        document.getElementById('btn').onclick = debounce(() => {
            console. Log ("triggered")
        }, 2000)
    </script>
</body>
 
</html>

12. JS garbage collection mechanism

To solve the memory leak, the garbage collection mechanism will periodically (periodically) find out the memory (variables) that are no longer used, and then release its memory.

Now, there are two garbage collection mechanisms commonly used by major browsers: tag clearing and reference counting.
Mark clear
The most common garbage collection method in JS is tag cleanup. When a variable enters the environment, for example, if a variable is declared in a function, it will be marked as “entering the environment”. Logically, the memory occupied by the entering environment variables can never be released, because they may be used as long as the execution flow enters the corresponding environment. When a variable leaves the environment, it is marked as “leaving the environment”.

function test(){
    var a = 10;    // Marked "into the environment"
    var b = "hello";    // Marked "into the environment"
}
test();    // After execution, a and B are marked "leave the environment" and recycled

When the garbage collection mechanism is running, it will mark all variables stored in memory (it can be any marking method), and then it will remove the variables in the environment and the variable marks (closures) referenced by the variables in the environment. After that, the remaining marked variables are regarded as variables to be deleted because they are no longer accessible to variables in the environment. Finally, when the garbage collection mechanism runs in the next cycle, it will free the memory of these variables and reclaim the space they occupy.

So far, the JS implementations of IE, Firefox, opera, chrome and safari all use the garbage collection strategy of tag removal or similar strategies, but the garbage collection intervals are different from each other.
Reference count
The language engine has a “reference table”, which stores the reference times of all resources (usually various values) in memory. If the number of references of a value is 0, it means that the value is no longer used, so this memory can be released.

JS interview related questions

In the figure above, the two values in the lower left corner have no reference, so they can be released.
If a value is no longer needed, but the number of references is not 0, the garbage collection mechanism cannot free this memory, resulting in memory leakage.

const arr = [1,2,3,4];
console.log("hello world");

In the above code, the array [1,2,3,4] is a value, which will occupy memory. The variable arr is the only reference to this value, so the number of references is 1. Although the following code does not use arr, it will continue to occupy memory.

If you add a line of code and remove the ARR reference to [1,2,3,4], this memory can be released by the garbage collection mechanism.

let arr = [1,2,3,4];
console.log("hello world");
arr = null;

In the above code, when arr is reset to null, the reference to [1, 2, 3, 4] is released. The number of references becomes 0, and the memory can be released.

Therefore, it does not mean that with garbage collection mechanism, programmers will be relaxed. You still need to pay attention to memory usage: those values that take up a lot of space must be checked once they are no longer used
Whether there are still references to them. If 6 it is, you must dereference it manually

13. Commonjs, AMD and CMD

Why modules are important, because with modules, we can more easily use other people’s code and load what modules we want.
So the following three modules.
Commonjs: start with server-side modularization and synchronization defined modularization. Each module is a separate scope, module output, modules Exports, module loading requires() to import the module.
AMD: the Chinese name means asynchronous module definition

After nodejs based on the commonjs specification came out, the concept of server-side module has been formed. Naturally, we want client-side module. And it is best that the two can be compatible. A module can run on both the server and the browser without modification. However, due to a major limitation, the commonjs specification is not suitable for browser environment. Or the above code. If it runs in the browser, there will be a big problem. Can you see it?

var math = require('math');

  math.add(2, 3);

The second line math Add (2, 3), run after the first line require (‘math ‘), so you must wait for math JS loading completed. In other words, if the loading time is long, the whole application will stop there and wait. You will notice that require is synchronized.

This is not a problem for the server side, because all modules are stored in the local hard disk and can be loaded synchronously. The waiting time is the reading time of the hard disk. However, for the browser, this is a big problem, because the modules are placed on the server side, and the waiting time depends on the speed of the network. It may take a long time, and the browser is in the “fake death” state.

Therefore, modules on the browser side cannot be loaded synchronously, but can only be loaded asynchronously. This is the background of AMD specification.
AMDIt is the abbreviation of “asynchronous module definition”, which means “asynchronous module definition”. It loads modules asynchronously, and the loading of modules does not affect the operation of subsequent statements. All statements that depend on this module are defined in a callback function. The callback function will not run until loading is completed.

Amd also uses the require () statement to load modules, but unlike commonjs, it requires two parameters:

require([module], callback);

The first parameter [module] is an array whose members are the modules to be loaded; The second parameter callback is the callback function after loading successfully. If the previous code is rewritten into amd form, it is as follows:

require([‘math’], function (math) {

math.add(2, 3);

});

math. Add () is not synchronized with math module loading, and the browser will not fake death. So obviously, AMD is more suitable for browser environment. At present, there are mainly two JavaScript libraries that implement amd specification:require.jsandcurl.js

CMD
The common module definition specification is very similar to AMD. Keep it as simple as possible and is similar to commonjs and node JS module specification maintains great compatibility.

define(function(require, exports, module) {
  var $ = require('jquery');
  var Spinning = require('./spinning');
  exports.doSomething = ...
  module.exports = ...
})

14. Light copy and deep copy

https://blog.csdn.net/jiang7701037/article/details/98738487
methodhttps://www.cnblogs.com/echolun/p/7889848.html

15. Encapsulate native Ajax into promise

var  myNewAjax=function(url){
return new Promise(function(resolve,reject){
var xhr = new XMLHttpRequest();
xhr.open('get',url);
xhr.send(data);
xhr.onreadystatechange=function(){
if(xhr.status==200&&readyState==4){
var json=JSON.parse(xhr.responseText);
resolve(json)
}else if(xhr.readyState==4&&xhr.status!=200){
reject('error');
}
}
})
}

16. Achieve two columns of equal height

https://blog.csdn.net/dizuncainiao/article/details/78191815
http://www.cssaaa.com/skill/163.html

17. Code execution sequence

https://www.cnblogs.com/wangziye/p/9566454.html

setTimeout(function(){console.log(1)},0);
new Promise(function(resolve,reject){
console.log(2);
resolve();
}).then(function(){console.log(3)
}).then(function(){console.log(4)});
process.nextTick(function(){console.log(5)});
console.log(6);

Output 2.6 5.3.4.1
Execution sequence
Script (main program code) – > process nextTick—>Promises…——> setTimeout——>setInterval——>setImmediate——> I/O——>UI rendering

18. How to achieve sleep effect

1. While loop mode

function sleep(ms){
var start=Date.now(),expire=start+ms;
while(Date.now()<expire);
console.log('1111');
return;
}

After sleep (1000) is executed, 1111 is output after sleeping for 1000ms. The disadvantages of the above circulation mode are obvious, which is easy to cause dead circulation.
2. It is realized through promise

function sleep(ms){
var temple=new Promise(
(resolve)=>{
console.log(111);setTimeout(resolve,ms)
});
return temple
}
sleep(500).then(function(){
//console.log(222)
})

//111 is output first, and 222 is output after a delay of 500ms
3. Async encapsulation

function sleep(ms){
return new Promise((resolve)=>setTimeout(resolve,ms));
}
async function test(){
var temple=await sleep(1000);
console.log(1111)
return temple
}
test();

//1111 is output with a delay of 1000ms
4. It is realized through generate

function* sleep(ms){
yield new Promise(function(resolve,reject){
console.log(111);
setTimeout(resolve,ms);
})
}
sleep(500).next().value.then(function(){console.log(2222)})

19. JS judge the data type

1.typeof
The returned data types include number, Boolean, symbol, string, object, undefined and function.
Typeof null, return type error, return object
2. ToString is the most perfect

Object.prototype.toString.call('') ;   // [object String]
Object.prototype.toString.call(1) ;    // [object Number]
Object.prototype.toString.call(true) ; // [object Boolean]
Object.prototype.toString.call(Symbol()); //[object Symbol]
Object.prototype.toString.call(undefined) ; // [object Undefined]
Object.prototype.toString.call(null) ; // [object Null]
Object.prototype.toString.call(new Function()) ; // [object Function]
Object.prototype.toString.call(new Date()) ; // [object Date]
Object.prototype.toString.call([]) ; // [object Array]
Object.prototype.toString.call(new RegExp()) ; // [object RegExp]
Object.prototype.toString.call(new Error()) ; // [object Error]
Object.prototype.toString.call(document) ; // [object HTMLDocument]
Object. prototype. toString. call(window) ; // [object global] window is a reference to the global object global

3.constructor
Constructor is an attribute of the prototype prototype. When a function is defined, the JS engine will add the prototype prototype for the function, and the constructor attribute in the prototype points to the function reference. Therefore, rewriting the prototype will lose the original constructor.
4. instanceof
Instanceof is used to judge whether a is an instance of B. the expression is: a instanceof B. If a is an instance of B, it returns true; otherwise, it returns false. Special attention should be paid here: instanceof detects prototypes,

Instanceof can only be used to judge whether two objects belong to the instance relationship, but not the specific type of an object instance.

20. Common methods of JS array

1. Array.map()
This method calls a provided function for each element in the array, and the result is returned as a new array without changing the original array

let arr = [1, 2, 3, 4, 5]
    let newArr = arr.map(x => x*2)
    //Arr = [1, 2, 3, 4, 5] the original array remains unchanged
    //Newarr = [2, 4, 6, 8, 10] returns a new array

2. Array.forEach()
This method executes each element in the array and passes it into the provided function. There is no return value. Note that it is different from the map method

let arr = [1, 2, 3, 4, 5]
   num.forEach(x => x*2)
   //Arr = [1, 2, 3, 4, 5] array change, pay attention to distinguish it from map

3.Array.filter()
This method judges all elements and returns the elements that meet the conditions as a new array

let arr = [1, 2, 3, 4, 5]
    const isBigEnough = value => value >= 3
    let newArr = arr.filter(isBigEnough )
    //Newnum = [3, 4, 5] the element satisfying the condition is returned as a new array

4.Array.every()
This method is to judge all elements and return a Boolean value. If all elements meet the judgment conditions, it returns true, otherwise it is false:

let arr = [1, 2, 3, 4, 5]
    const isLessThan4 = value => value < 4
    const isLessThan6 => value => value < 6
    arr.every(isLessThan4 ) //false
    arr.every(isLessThan6 ) //true

5. Array.some()
This method is to judge all elements and return a Boolean value. If all existing elements meet the judgment conditions, it returns true. If all elements do not meet the judgment conditions, it returns false:

let arr= [1, 2, 3, 4, 5]
    const isLessThan4 = value => value < 4
    const isLessThan6 = value => value > 6
    arr.some(isLessThan4 ) //true
    arr.some(isLessThan6 ) //false

6.Array.reduce()
This method is the return function of all element calls. The return value is the final result. The passed in value must be the function type:

let arr = [1, 2, 3, 4, 5]
   const add = (a, b) => a + b
   let sum = arr.reduce(add)
   //Sum = 15 is equivalent to the effect of accumulation
   There is also an array Reducereight() method, except that it operates from right to left

7. Array.push()
This method is to add a new element after the array. This method changes the length of the array:
8. Array.pop()
This method deletes the last element after the array and returns the array. This method changes the length of the array:

let arr = [1, 2, 3, 4, 5]
    arr.pop()
    console.log(arr) //[1, 2, 3, 4]
    console.log(arr.length) //4

9. Array.shift()
This method deletes the first element after the array and returns the array. This method changes the length of the array:

let arr = [1, 2, 3, 4, 5]
    arr.shift()
    console.log(arr) //[2, 3, 4, 5]
    console.log(arr.length) //4 

10.Array.unshift()
This method adds one or more elements to the beginning of the array and returns the length of the new array:

let arr = [1, 2, 3, 4, 5]
    arr.unshift(6, 7)
    console.log(arr) //[6, 7, 1, 2, 3, 4, 5]
    console.log(arr.length) //7 

11.Array.isArray()
Determines whether an object is an array and returns a Boolean value
12.Array.concat()
This method is a method that can splice multiple arrays into one array:

let arr1 = [1, 2, 3]
      arr2 = [4, 5]
  let arr = arr1.concat(arr2)
  console.log(arr)//[1, 2, 3, 4, 5]

13. Array.toString()
This method converts an array to a string:

let arr = [1, 2, 3, 4, 5];
   let str = arr.toString()
   console.log(str)// 1,2,3,4,5

14. Array. Splice (start position, number of deleted elements)

Universal method can realize addition, deletion and modification:

let arr = [1, 2, 3, 4, 5];
     let arr1 = arr.splice(2, 0 'haha')
     let arr2 = arr.splice(2, 3)
     let arr1 = arr.splice(2, 1 'haha')
     console. Log (Arr1) // [1, 2, 'haha', 3, 4, 5] add a new element
     console. Log (arr2) // [1, 2] delete three elements
     console. Log (arr3) // [1, 2, 'haha', 4, 5] replace an element

15.Array. sort()
If you want to sort according to other criteria, you need to provide a comparison function, which compares two values and returns a number indicating the relative order of the two values. The comparison function should have two parameters a and B, and its return values are as follows:

If a is less than B, a should appear before B in the sorted array, and a value less than 0 is returned.
If a equals B, 0 is returned.
If a is greater than B, a value greater than 0 is returned.

function sortNumber(a,b)
{
return a - b
}

var arr = new Array(6)
arr[0] = "10"
arr[1] = "5"
arr[2] = "40"
arr[3] = "25"
arr[4] = "1000"
arr[5] = "1"

document.write(arr.sort(sortNumber))

16.Array.reverse()
The reverse () method is used to reverse the order of the elements in the array.

21. Array de duplication

1. Use ES6 set to remove weight

Set: it can receive an array or class array object and automatically remove the duplicate.

Array. From: convert class array objects and iteratable objects into arrays.

JS interview related questions

2018062011354884.png

2. Use for to nest for, and then split to remove duplication

function unique(arr){            
        for(var i=0; i<arr.length; i++){
            for(var j=i+1; j<arr.length; j++){
                If (arr [i] = = arr [J]) {// the first one is equal to the second one, and the splice method deletes the second one
                    arr.splice(j,1);
                    j--;
                }
            }
        }
return arr;
}

3. Use indexof
The indexof () method returns the first occurrence of a specified string value in the string.

var arr = [1, 2, 2, 3, 4, 5, 5, 5, 6, 7, 7];
         var newArr = [];
         for (var i = 0; i < arr.length; i++) {
           If (newarr. Indexof (arr [i]) = = - 1) {// retrieve newarr from beginning to end and check whether it contains arr [i]
                 newArr. push(arr[i]);// If there is no arr [i], insert arr [i] into newarr
            }
        }

4. Use sort ()
Sort () sorting method is used, and then traversal and adjacent element comparison are carried out according to the sorted results.

function unique(arr) {
    if (!Array.isArray(arr)) {
        console.log('type error!')
        return;
    }
    arr = arr.sort()
    var arrry= [arr[0]];
    for (var i = 1; i < arr.length; i++) {
        if (arr[i] !== arr[i-1]) {
            arrry.push(arr[i]);
        }
    }
    return arrry;
}

5. Use includes
The includes () method is used to determine whether the string contains the specified substring.

Returns true if a matching string is found, otherwise false.

function unique(arr) {
    if (!Array.isArray(arr)) {
        console.log('type error!')
        return
    }
    var array =[];
    for(var i = 0; i < arr.length; i++) {
            If (! Array. Includes (arr [i])) {// includes detects whether the array has a value
                    array.push(arr[i]);
              }
    }
    return array
}

6. Use filter

function unique(arr) {
  return arr.filter(function(item, index, arr) {
    //Current element, the first index in the original array = = the current index value, otherwise the current element is returned
    return arr.indexOf(item, 0) === index;
  });
}

7. Using recursive de duplication

function unique(arr) {
        var array= arr;
        var len = array.length;

    array. Sort (function (a, b) {// it is more convenient to remove duplicates after sorting
        return a - b;
    })

    function loop(index){
        if(index >= 1){
            if(array[index] === array[index-1]){
                array.splice(index,1);
            }
            loop(index - 1);    // Recursive loop, and then array de duplication
        }
    }
    loop(len-1);
    return array;
}

22. Performance optimization

https://zhuanlan.zhihu.com/p/113864878?from_voters_page=true

https://blog.csdn.net/liujie19901217/article/details/52074018

23. Language features of JS

Run on the client browser;

Directly parse the execution code without precompiling;

It is a weakly typed language, which is more flexible;

Operating system independent, cross platform language;

Scripting language, explanatory language

24. Judge whether the variable is of array type

https://blog.csdn.net/lee_magnum/article/details/11555981

25. Function coritization

function curry(fn,val){
  return function(){
    //Convert to array
    var args = Array.from(arguments)
    if(val){
      //Parameter splicing
      args = args.concat(val)
    }
    //fn. Length indicates how many parameters the function needs to pass in
    //Recursive call stops recursion when the parameters are equal
    if(fn.length > args.length){
      return curry(fn,args)
    }
    return fn.apply(null,args)
  }
}
function sum(a, b, c) {
  console.log(a + b + c);
}
const fn = curry(sum);
fn(1,2,3)
fn(1)(2)(3)

26. Can the arrow function new

27. TS function overload

//The name of the function is the same, and the parameters and number of the function are different
    //Requirement: there is an add function, which can accept two parameters of sting type for splicing and two parameters of number type for addition

    //Function overload declaration
    function add(x:string,y:string) :string
    function add(x:number,y:number) :number

    function add(x:string|number,y:string|number) :string|number{
       if(typeof x ==='string' && typeof y ==='string'){
           Return x + Y // String splicing
       }

       else if(typeof x ==='number' && typeof y ==='number'){
         Return x + Y // add numbers
       }
    }

   console.log(add(1,2));
    
   console.log(add('11','22'));

//    console. log(add('11',12));  report errors

28. JS function overload

29. fetch

Fetch is known as an alternative to Ajax. It appears in ES6 and uses the promise object in ES6. Fetch is designed based on promise. Fetch’s code structure is much simpler than Ajax, and its parameters are a bit like jQuery Ajax. However, be sure to remember that fetch is not a further encapsulation of Ajax, but a native JS without using the XMLHttpRequest object.

30. RESTful

31. Underlying principles of echarts

1. Echarts is a lightweight JavaScript graphics library, pure JS implementation, MVC encapsulation and data-driven.
2. Svg and canvas are two optional class libraries. SVG has better interactivity and weak performance. It is not suitable for the mobile terminal and will crash when drawing tens of thousands of points. The rendering speed and performance of canvas are better. Echarts constructs an MVC layer on canvas, so that it can interact like SVG.
3. Echarts features: the importance and priority decrease in turn, the design effect is intuitive and vivid, interactive and personalized.
4. The overall structure of echarts is based on MVC architecture, and the main functions of each part are:
Storage (m): model layer, which realizes curd (addition, deletion, modification and query) management of graphic data;
Painter (V): view layer, which realizes the life cycle management of canvas elements, that is, view rendering, update control and drawing;
Handler (c): control layer, event interactive processing, and complete DOM event simulation encapsulation.

Storage is a similar data warehouse, which provides operations such as reading, writing, modifying and deleting various data. Painter holds the storage object, that is, painter reads the storage object for drawing. The handler holds the storage object and painter object, and the control layer has curd relationship with the model layer, that is, the handler realizes the data part required for event interactive processing by accessing the data addition, deletion, modification and query operations provided by the storage object; There is a call relationship between the control layer and the view layer, that is, the handler realizes the view part of event interactive processing by accessing the view operation provided by the painter object.

32. WebSocket

The difference and connection between websocket and ajax

33. A = A. x = {X: 1} how to understand

https://blog.csdn.net/qiphon3650/article/details/78860973

34. What is the difference between JavaScript and Java

  1. Object based and object-oriented: Java is a real object-oriented language. Even when developing simple programs, objects must be designed; JavaScript is a scripting language, which can be used to make complex software that has nothing to do with the network and interacts with users. It is an object-based and event driven programming language, so it itself provides very rich internal objects for designers to use.
  2. Interpretation and compilation: Java source code must be compiled before execution. JavaScript is an interpretative programming language. Its source code does not need to be compiled and is interpreted and executed by the browser. (almost all current browsers use JIT (just in time compilation) technology to improve the running efficiency of JavaScript)
  3. Strongly typed variables and weakly typed variables: Java adopts strongly typed variable checking, that is, all variables must be declared before compilation; Variables in JavaScript are weakly typed, and can not be declared even before using variables. The JavaScript interpreter checks and infers their data types at run time.
  4. The code format is different.
  5. JavaScript and Java are two different products developed by two companies. Java is an object-oriented programming language launched by the original Sun Microsystems company, which is especially suitable for Internet application development; JavaScript is a product of Netscape company. In order to expand the function of Netscape browser, it is an object-based and event driven explanatory language that can be embedded in web pages. The predecessor of JavaScript is livescript; The predecessor of Java is oak language.

35. What is the difference between ts and JS

  1. TS is a static class language, which can be declared as a document. JS is a dynamic class language, which is relatively more flexible.
  2. If you write a button component with TS, you can clearly know whether buttonprops must be transmitted Optional. What type is style and what type is disabled? It is easier to maintain and expand than JS and ts. the code can be annotated to avoid the embarrassment of missing 3 in a month and forgetting what the code has written,
  3. Compared with JS, TS adds void / never / any / tuple / enumeration / and some advanced types
  4. JS does not have the concept of overloading, and ts can overload
  5. Vscode / IDE has very friendly tips for ts
  6. TS is more conducive to reconfiguration

36. Execute function now

37. Symbol

38. Handwritten compose

function compose() {
  var args = arguments;
  var start = args.length - 1;
  return function () {
    var i = start - 1;
    var result = args[start].apply(this, arguments);
    while (i >= 0){
      result = args[i].call(this, result);
      i--;
    }
    return result;
  };
}
------------------------------------------
function addHello(str){
    return 'hello '+str;
}
function toUpperCase(str) {
    return str.toUpperCase();
}
function reverse(str){
    return str.split('').reverse().join('');
}
var composeFn=compose(reverse,toUpperCase,addHello);
console.log(composeFn('ttsy'));  // YSTT OLLEH

39. Long interview talk

40. DOM browser object locaiton

Recommended Today

Test and development. Python + flask implements the interface to receive disk information

Today’s sharing is based on: Test Development: Python + flask implementation interface receives memory information to further share how to use Python + flask implementation to receive disk information. Principle: Call the shell script through Python to execute the relevant commands of disk, then process them, and then request the requests library to push data […]