Front end of the interview

1. Js executes multiple asynchronous functions sequentially

Const p1 = () => new Promise((resolve, reject) => {setTimeout(() => {resolve("p1")); }, 1000); }); const p2 = () => new Promise((resolve, reject) => { setTimeout(() => { resolve("p2"); }, 500); }); const p3 = () => new Promise(() => { setTimeout(() => { resolve("p3"); }, 100); }, 100); Const fnArr = [p1, p2, p3]; / / 3, define execution function const run = (arr, start = 0) = > {/ / parameter start cannot exceed arr. Length if (start > arr. Length | | start < 0) {return; } const next = (i) => { if (i < arr.length) { const fn = arr[i]; fn().then((res) => { console.log(res); i++; next(i); }); }}; next(start); }; // 4. Run (fnArr);Copy the code

Address: online codesandbox. IO/s/competent…

2. Change data in data in computed in VUE

// Returns an error during computed data modification. New Vue({data() {return {ABC: '123'}; new Vue({data() {return {ABC: '123'}; }, computed: {// Change data doubleAbc using get and set: {get: function() {return this.abc * 2; }, set: function(newVal) { this.abc = newval; }}}})Copy the code

3, if you

const debounce = (fn, waitTime) => {
    let timer = null;
    return function() {
        const _this = this;
        const args = arguments;
        
        clearTimeout(timer);
        
        timer = setTimeout(() => {
            fn.call(_this, args);
        }, waitTime)
    }
};
Copy the code

4, This question

How to determine exactly what this refers to?

1. Whether the function is called in new (new binding), if so, then this is bound to the newly created object

2. Whether the function is called by call, apply, or bind. If so, this binds to the specified object

3. Whether the function is called from a context object (implicitly bound), and if so, this binds to that context object

4. If none of the above, use the default binding, undefined if in strict mode, global otherwise

5. If you pass null or undefined as this to call, apply, or bind, these values will be ignored and the default binding rules will apply

6. If it is an arrow function, this inherits from this in the outer code block

Var name1 = 'koala'; var name1 = 'koala'; var name1 = 'koala'; Var person1 = {name: 'programmer growth refers to north ', sayHi: sayHi } function sayHi(){ setTimeout(function(){ console.log('Hello,', this.name1); }) } person1.sayHi(); // Hello, koala setTimeout(function(){ person1.sayHi(); }, 200); // Hello, koalaCopy the code

What’s the difference between Interface and Type in TypeScript?

The same

1. Both describe an object or a function

interface

interface User {
    name: string;
    age: number;
}

inteface SetUser {
    (name: string, age: number): void;
}
Copy the code

type

type User = {
    name: string;
    age: number;
};

type SetUser = (name: string, age: number) => void;
Copy the code

2. Both allow extends

Interface and Type can both extend, and they are not independent of each other, meaning that interface can extend Type and Type can extend Inteface. The effect is similar, but the syntax is different.

interface extends interface

interface Name {
    name: string;
}

interface User extends Name {
    age: number;
}
Copy the code

type extends type

type Name = {
    name: string;
}

type User = Name & { 
    age: number; 
}
Copy the code

interface extends type

type Name = {
    name: string;
}

interface User extends Name {
    age: number;
}
Copy the code

type extends interface

interface Name {
    name: string;
}

type User = Name & {
    age: number;
}
Copy the code

The difference between

Type B

  1. Type can declare basic type aliases, union types, tuples, and so on
// Basic type type Name = string; // interface Dog {wong(); } interface Cat { miao(); } type Pet = Dog | Cat; // Specify the type of each position in the array type PetList = [Dog, Pet];Copy the code
  1. The type statement can also be assigned to the typeof the instance obtained using typeof
// when you want to get the typeof a variable, use typeof
let div = document.createElement('div');
type B = typeof div;
Copy the code
  1. Other operations
type StringOrNumber = string | number;
type Text = string | {text: string};
type NameLookUp = Dictionary<string, Person>;
type Callback<T> = (data: T) = > void;
type Pair<T> = [T, T];
type Coordinates = Par<number>;
type Tree<T> = T | { left: Tree<T>, right: Tree<T> };
Copy the code

Interface works and type doesn’t

  1. Interface can declare merge
interface User {
    name: string;
    age: number;
}

interface User {
    sex: string;
}

const user: User = {
    name: 'test'.age: 12.sex: 'male'
};
Copy the code

6. Coriolization of functions

const curry = (func: Function. args:any[]) = > {
    // Get the number of arguments to the function
    const fnLen: number = func.length; // length is an attribute of the js function object. The value refers to 'how many arguments must be passed to the function', i.e. the number of parameters
    
    return function(. innerArgs:any[]) {
        innerArgs = args.concat(innerArgs);
        
        // If the parameters are collected enough, continue recursive collection
        if(innerArgs.length < fnLen) {
            // @ts-ignore
            return curry.call(this, func, ... innerArgs); }else {
            // Otherwise call func with the search parameters
            // @ts-ignore
            func.apply(this, innerArgs); }}; };/ / test
const add = curry((num1: number, num2: number, num3: number) = > {
    console.log(num1, num2, num3, num1 + num2 + num3);
});

// @ts-ignore
add(1) (2) (3) // 1 2 3 6
// @ts-ignore
add(1.2) (3) // 1 2 3 6
add(1.2.3) // 1 2 3 6
// @ts-ignore
add(1) (2.3) // 1 2 3 6
Copy the code

The online preview: [codesandbox. IO/s/admiring -…

7. List to tree structure

interface ArrayItem {
    id: number;
    name: string;
    pid: number;
}

/** * List to tree structure *@param Array Passes an array *@param ItemId Key * corresponding to the subitem ID@param ParentId Key */ corresponding to the parent item ID in the child item
const arrayToTree = (array: ArrayItem[], itemId = 'id', parentId = 'pid') = > {
    const hashMap: any = {};
    const result: any[] = [];
    
    array.forEach((it: ArrayItem) = > {
       const id = it[itemId];
       const pid = it[parentId];
       
       // If the tree does not exist, declare the children tree first
       if(! hashMap[id]) { hashMap[id] = {children: []
           };
       }
       
       hashMap[id] = {
           ...it,
           children: hashMap[id].children
       };
       
       // Process the current item
       const treeIt = hashMap[id];
       
       // Root node, push directly
       if (pid === 0) {
           result.push(treeIt);
       } else {
           // It is also possible that the parent of the current node has not yet joined the hashMap and needs to be handled separately
           if(! hashMap[pid]) { hashMap[pid] = {chilren: []}; }// If it is not the root node, find the parent node and insert yourself into the children of the parent nodehashMap[pid].children,push(treeIt); }});return result;
};

/ / test
const data: ArrayItem[] = [
    { id: 2.name: '2'.pid: 1 },
    { id: 1.name: '1'.pid: 0 },
    { id: 3.name: '3'.pid: 1 },
    { id: 4.name: '4'.pid: 3 },
    { id: 5.name: '5'.pid: 4 },
    { id: 7.name: '7'.pid: 6},]console.log(arrayToTree(data));
Copy the code

8. Tree structure transfer list

// Tree structure list
const treeToList = (tree: any[]) = > {
    const list = [];
    const queue = [...tree];

    while (queue.length) {
        // Start fetching nodes from the front
        const node = queue.shift();
        const children = node.children;
        // Take the children of the current node and queue them for the next loop
        if(children.length) { queue.push(... children); }// Delete the extra children tree
        delete node.children;
        // Add to the list
        list.push(node);
    }

    return list;
};

const dataTree = [
    {
        "id": 1."name": Department of "1"."pid": 0."children": [{"id": 2."name": "Department of 2"."pid": 1."children": []}, {"id": 3."name": "Unit 3"."pid": 1."children": [{"id": 4."name": "Department of 4"."pid": 3."children": [{"id": 5."name": Department of "5"."pid": 4."children": []}]}]}];console.log(treeToList(dataTree));
Copy the code

What is the prototype chain

In JavaScript everything is an object, and objects have relationships with each other, not in isolation. In JavaScript, the inheritance relationship between objects is that the prototype Object points to the parent Object until it points to the Object Object. In this way, a prototype pointing chain is formed. The technical term is called prototype chain.

10. Deep copy

/ / copy
function checkType(any) {
    return Object.prototype.toString.call(any).slice(8, -1)}function deepClone(any){
    if(checkType(any) === 'Object') { // Copy objects
        let o = {};
        for(let key in any) {
            o[key] = deepClone(any[key])
        }
        return o;
    } else if(checkType(any) === 'Array') { // Copy the array
        let arr = []
        for(let i = 0,length = any.length; i<length; i++) { arr[i] = deepClone(any[i]) }return arr;
    } else if(checkType(any) === 'Function') { // Copy the function
        return new Function('return '+any.toString()).call(this)}else if(checkType(any) === 'Date') { // Copy the date
        return new Date(any.valueOf());
    } else if(checkType(any) === 'RegExp') { // Copy the re
        return new RegExp(any)
    } else if(checkType(any) === 'Map') { // Copy the Map collection
        let m = new Map()
        any.forEach((v,k) = >{
            m.set(k, deepClone(v))
        })
        return m
    } else if(checkType(any) === 'Set') { // copy the Set
        let s = new Set(a)for(let val of any.values()) {
            s.add(deepClone(val))
        }
        return s
    }
    return any;
}

const o = {
    name: 'Joe'.skills: ['play'.'running'.'Play badminton'].age: 18.love: {
        name: 'little red'.age: 16
    },
    map: new Map([['aaa'.'123']]),
    fn:function(a){
        console.log('My name isThe ${this.name}` + a)
    },
    set: new Set([1.2.3.4.5]),
    date: new Date(),
    reg: new RegExp('abc')}const cloneO = deepClone(o);
cloneO.fn('test');
console.log(cloneO);
Copy the code