Interview summary of Shanghai Lilis, MIHA tour, B station, little red book, dewu and other Internet companies

Time:2021-1-23

preface

Currently working in Hangzhou, many of my friends have moved to Shanghai. Encouraged by my friends, Jin jiuyinshi has invested in several Internet companies in Shanghai. Most of the interviewees are middle and senior front-end positions, and they are lucky to get offers. I’ve been interviewing for a long time. I’m free to record the interview record.

In the article, I will not only list the interview questions, but also give some suggestions on the answers. Basically, all the questions are answered at the end of the interview. If the space is limited, it will not be started. My personal ability is limited, and I can’t guarantee that my answers are correct. If there are any mistakes, I hope to correct them. The ranking of topics is not divided into priority and company. It is simply classified, that is, it is a pure record, which is a very conventional topic.

Companies interviewed

Lilis, mihayou, BiliBili, xiaohongshu, Weimeng, dewu, etc. This article mainly records the second-line Internet companies interviewed, and of course, also met Ali, meituan, pinduoduo and other companies. If you count them into the first-line camp, there is no record here. See the next one for details!
Interview summary of Shanghai Lilis, MIHA tour, B station, little red book, dewu and other Internet companies

comprehension question

1. How to realize lazy loading of pictures

Three judgment methods are provided to judge whether the image is in the visible area or not, and move the image to the visible area for loading

  1. offsetTop < clientHeight + scrollTop
  2. element.getBoundingClientRect().top < clientHeight
  3. IntersectionObserver
2. How to deal with cross domain

There are too many solutions for cross domain processing. Our company mainly forwards the request through nginx. The address of the front-end request is consistent with the page address, so there is no cross domain processing. Nginx forwards the request to the correct service. Page address: web.taobao.com , request interface address web.taobao.com/api . taobao.com/*

3. Can the form cross domain

Form submission can be cross domain and is not limited by the browser’s homologous policy. It is estimated that it is a legacy of history. It is also possible that JS cannot be obtained as a result of form submission, so it is not a big problem not to restrict it. However, there is a problem, that is, CSRF attack, which is not carried out specifically, because it can automatically bring a cookie to cause the attack to succeed, and the new attribute samesite of cookie can be used to limit this situation

4. Why do you say JS is single thread, not multi thread? Tell me your understanding

JavaScript’s single thread is related to its purpose. As a browser scripting language, JavaScript is mainly used to interact with users and operate dom. This determines that it can only be a single thread, otherwise it will bring a very complex synchronization problem. For example, suppose JavaScript has two threads at the same time. One thread adds content to a DOM node, and the other thread removes the node. Which thread should the browser follow?

5. Why can typeof detect types? Is there a better way

Typeof is generally used to determine the type of a variable. We can use typeof to determine number, string, object, Boolean, function, undefined, This kind of judgment can help us solve some problems. When JS stores variables in the bottom layer, it will store its type information in the lower 1-3 bits of the machine code of the variable (000: object, 010: floating point, 100: string, 110: Boolean, 1: integer), but null all the machine codes are 0, which are directly treated as objects.
So, is there a better way to distinguish types

6. Talk about your understanding of graphql

Graphql provides an easy to understand and complete description of the data in your API, so that the client can accurately obtain the data it needs without any redundancy. It also makes it easier for the API to evolve over time, and can be used to build powerful developer tools.

  1. With the emergence of multiple terminals, app, applet and PC all need the same interface, but there are some differences. Several sets of conventional interfaces need to be provided. For graphql, you only need to write query statements
  2. It’s a natural aggregation interface. In the past, a page needed to request different data. We can request multiple interfaces. We can let the server aggregate. With graphql, we can aggregate the data we want
  3. You don’t have to worry about the version. Before, when writing interfaces, in order to be compatible with old projects, you can access them normally, especially for app and online projects. Our interfaces certainly can’t affect online projects. So when there are relatively big changes, you can only upgrade the version. With graphql, you don’t need to care about the version. Just change the query statement of the interface
  4. Migration is very simple, the server in the previous interface on a little transformation is good, front-end write query statements

Interview summary of Shanghai Lilis, MIHA tour, B station, little red book, dewu and other Internet companies

7. What is event delegation? What are the benefits of it?

Event delegation uses event bubbling mechanism to process and specify an event handler to manage all events of a certain type
Using the principle of bubbling, the event is added to the parent to trigger the execution effect. In this way, only a piece of memory is opened up, which saves resources, reduces DOM operation and improves performance
Dynamic binding events, new elements in the list do not need to be rebound

8. How to use js to change the URL without refreshing the page?

The purpose of changing the URL is to let JS get different parameters and render different pages, which is actually the principle of Vue router

The simplest way is to change the hash. Changing the hash will not refresh the page. It will also change the URL and listen to the hashchange event to render the page

Another is to use history.pushState () method, which can also change the URL without refreshing the page, but this method can’t trigger the popstate event. However, pushstate enables us to trigger it manually, and we can’t know if the URL has changed. In fact, we don’t need to listen to the popstate to get the parameters of the URL change and render the page

9. What’s a better way to achieve a continuous animation of JS?

Using the request animation frame

10. What are the advantages of using CSS3 animation instead of JS animation?

CSS and JS animation have their own advantages and disadvantages

  1. Does not occupy JS main thread
  2. Hardware acceleration can be used
  3. The browser can optimize the animation (no animation when the element is not visible, reducing the impact on FPS)
Use and trigger of custom event in 11. JS
var event = new Event('build');

// Listen for the event.
elem.addEventListener('build', function (e) { ... }, false);

// Dispatch the event.
elem.dispatchEvent(event);
12. If you were asked to choose one of Vue / react / angularjs, which would you choose? Give me your reasons

Look at the team. Everyone can accept it. I’m a little familiar with Vue and react

13. Why use JSX to develop Vue

JSX is more flexible, using the idea of writing JS to write html is more efficient

14. Please explain how jsonp works

Jsonp is an informal transport protocol, which allows users to pass a callback to the server. When the server returns data, it will use the callback parameter as a function name to wrap the JSON data, so that the client can customize its own function to automatically process the returned data. When the get request returns from the background page, a JavaScript code can be returned, which will be executed automatically and can be used to call a callback function in the background page.

15. How to create a worker thread in JavaScript?

Just look at the document. In fact, I only used it once in a project, not often

16. What do you think is the main difference between PC development and mobile development?

It’s different from person to person

17. How do you debug when doing mobile development?

The most used are Charles and chrome://inspect/#devices Debugging, of course, the actual development or use the chrome development tool, the real machine is the use of Charles agent or chrome://inspect/#devices Agent, IOS, then use Safari real machine debugging, of course, also used vconsole, weinre debugging

18. How to realize the adaptation of H5 mobile terminal?

Flexible + REM for adaptation

Interview summary of Shanghai Lilis, MIHA tour, B station, little red book, dewu and other Internet companies

19. How to solve the problem of 1px in mobile terminal?

Pseudo element scaling

20. CSS box model

Ie box model, regular box model and other derived problems

21. How to realize skin changing function

I haven’t done this either. After checking, some students gave me a more detailed planhttps://juejin.im/post/684490…

22. How does hybrid communicate?
  1. The principle of API injection is that native gets the JavaScript environment context, and directly mounts objects or methods on it, so that JS can be called directly. Android and IOS have corresponding mounting methods respectively
  2. Prompt / console / Alert interception in WebView usually uses prompt, because this method is used less frequently in the front end, so there is no conflict
  3. WebView URL scheme jump interception

Interview summary of Shanghai Lilis, MIHA tour, B station, little red book, dewu and other Internet companies

23. Can you say something about weex?

There is an article above that says very clearly:https://zhuanlan.zhihu.com/p/…

Interview summary of Shanghai Lilis, MIHA tour, B station, little red book, dewu and other Internet companies

24. Please describe the ways to improve the page performance and how to optimize the loading of the home page?

There are too many things to talk about. I’ve torn up what I know, and then I’ve torn up what I actually use

25. How to optimize performance?

ditto

26. What do you know about front-end performance optimization solutions?

ditto

27. Can you talk about page caching?

The cache of strong cache protocol is not discussed in detail

What’s the difference between 28. JS animation and CSS animation?

I don’t want to elaborate on it. I can put it into performance optimization

58. What’s the difference between synchronous and asynchronous?

synchronizationIt can be understood that after executing a function or method, the program has been waiting for the system to return a value or message. At this time, the program is blocked, and only after receiving the returned value or message can it execute other commands.  asynchronousAfter the function or method is executed, there is no need to wait for the return value or message, just delegate one to the systemasynchronousWhen the system receives the return value or message, the system will automatically trigger the delegationasynchronousProcess, so as to complete a complete process.

60. What are the ways to realize asynchronous programming? Which is recommended?

Callback function, generator, promise, async / await

59. Introduce the features, advantages and disadvantages of promise, and how to implement it internally?

Promise is an asynchronous solution. The promise object accepts a callback function as a parameter. The callback function accepts two parameters, namely, callback resolve when success and callback reject when failure. In addition to the normal value, the parameter of resolve may also be an instance of a project object. The parameter of reject is usually an instance of an error object.

  1. The advantage is a better asynchronous solution
  2. The disadvantage is that promise cannot be cancelled. Once it is created, it will be executed immediately and cannot be cancelled halfway

Interview summary of Shanghai Lilis, MIHA tour, B station, little red book, dewu and other Internet companies

Can 30. HTTPS requests be intercepted and how to do it?

It’s entirely possible. Otherwise, how does Charles capture packets work? Of course, the premise is that the corresponding certificate is installed on the client

31. How does HTTPS ensure the security of data transmission?

Transmission encryption ah, the specific process is more complex, you can start an article

32. How about symmetric and asymmetric encryption?

The efficiency of asymmetric encryption is very low, only in the certificate verification stage, symmetric encryption in the data transmission stage

33. Can you tell me what security problems you encountered in your project and how to solve them?

XSS, CSRF, reptiles, wool collection and other security issues

Transmission encryption, interface signature, environment variable, token, input verification, etc

34. What’s the difference between XSS and CSRF?

There are a lot of specific things that can be said, and I won’t talk about them here

XSS front-end is mainly to control the input, cookie settings HTTP only

CSRF needs strict cookie policy and token verification

35. Do you think the parameters of the front-end transmission process need to be encrypted? Why? How can encryption be more secure?

Depending on the situation, the general request parameters: search keywords, paging parameters, there is no need for any encryption. Special field: ID verification must be encrypted. At the same time, the front-end game data must be encrypted, not only encrypted, but also signed.

36. What is man in the middle attack?

Man in the middle attack means that the attacker creates independent contact with both ends of the communication and exchanges the data they receive, so that both ends of the communication think that they are talking directly with each other through a private connection, but in fact the whole conversation is completely controlled by the attacker.

Interview summary of Shanghai Lilis, MIHA tour, B station, little red book, dewu and other Internet companies

37. What to do if the speed of webpack is too slow?

Using high version of webpack, multi thread / multi instance construction, reducing the scope of packaging, making full use of cache to improve the speed of secondary construction, DLL

38. What’s the difference between loader and plugin?

Loader, which is a converter, compiles a file into B file, for example, converts A.less to a.css, a simple file conversion process.

Plugin is an extender, which enriches the webpack itself. For the whole process of webpack packaging after the loader is finished, it does not directly operate files, but works based on the event mechanism. It will listen to some nodes in the process of webpack packaging and perform a wide range of tasks

40. Has plugin been written in the project?

The project has written several plug-ins for processing packaged files, so let’s talk about them briefly

41. Have you used any other packaging tools besides webpack?

Rollup et al

42. Do you know the difference between NPM Ci and NPM install?

NPM install read package.json To create a dependency list and use package- lock.json Tell you which version of these dependencies to install. If the dependency is not in package- lock.json It will be added by NPM install.

NPM CI (named after continuous integration) directly from package- lock.json Install dependencies and use only package.json To verify that there are no mismatched versions. If any dependencies are missing or the version is incompatible, an error is thrown.

In terms of speed, CI is obviously faster than install, and CI is better than install in online publishing and packaging

43. Can you tell us the principle of Vue’s response

This topic can say a lot of things, each point can be expanded, mainly to see their familiarity with the source code, you can say Object.defineProperty It can be said that watcher can start from all aspects, and it can also explain the process from how to render the change of a variable to the real dom. It’s good to make it clear

Interview summary of Shanghai Lilis, MIHA tour, B station, little red book, dewu and other Internet companies

44. What do you know about vue3.0?

Proxy, composition API, typescript, etc

Why should composition API be introduced in 45. Vue3.0?
  1. For better code organization, the options API causes code to jump around
  2. Logical reuse is more convenient. Although mixin can reuse code well, when there are too many mixins, you don’t know where the variables come from, which will also cause naming conflicts
  3. There is no such thing as this
46. Does bidirectional binding conflict with vuex?

There are conflicts. In fact, there are explanations on the official websitehttps://vuex.vuejs.org/zh/gui…
V-model will modify the value of state, but the modification of vuex data must go through the mutation, so there is a conflict
The simple way is not to use V-model, you can do data binding by yourself

47. How to solve the state data loss of vuex after page refresh?

The data in the store is stored in the running memory. When the page is refreshed, the page will reload the Vue instance, and the data in the store will be reset and initialized. Theoretically, we don’t need to store the value of vuex persistently, because we will go to the interface to get the data and re render it, just like the first time
But if you have to save the last temporary state, you can use localstorage for persistent storage, but at this time you have to deal with the problem of data synchronization with the server

48. Why should we have vuex and use local storage?

Vuex is a Vue.js The state storage of vuex is responsive to the state management mode of application development. When Vue components read the state from the store, if the state in the store changes, the corresponding components will be updated efficiently.
When multiple components have the same state, vuex can help us deal with it well
You can use Vue developer tools to debug the state of vuex
These advantages can not be well simulated

50. The native addeventlisteners in the Vue component listen to events. Do you want to destroy them manually? Why?

Manually destroy before destroy. Otherwise, if you use addeventlisteners in mounted, you may repeatedly register and cause memory leak.

51. Can you tell me how your project code is organized?

Briefly describe the various project templates used in the work, the scenarios used, how the templates organize the code, the reasons for such organization, as well as the technical selection, single page or multi page, template or JSX, JS or ts, etc

52. What do you think of overtime?

It’s understandable to work overtime properly, but it’s unacceptable to work overtime without pay

53. What are the difficulties in the project and how to solve them?

Everyone’s situation is different, maybe it’s a technical problem, maybe it’s a project promotion problem, anyway, I said something about everything

54. How to manage your own projects?

To understand the project from a product’s attitude, to follow up the project from a PM’s attitude, to realize the project from a technical perspective, to describe how to participate in a project from various aspects, as well as the follow-up data tracking, problem review, summary and promotion of the project

55. How to write the technical documents of the project and how to do the project review?

Usually, the technical documents are written on the basis of being familiar with the requirements documents, such as business process, technology selection, interface definition (some front-end, some back-end, we don’t have a strong ownership), and then interface with the back-end, and develop after setting the interaction mode
Project review is mainly from the problems encountered in the project, data, etc. review, said a lot

56. What is the front-end infrastructure of the company? Have you ever participated in the development?

From its own situation, whether it has written component library, whether it has participated in the development of any system, and its own role

57. Teamwork, previous development process?

Open topic, describe the actual situation

Interview summary of Shanghai Lilis, MIHA tour, B station, little red book, dewu and other Internet companies

Programming questions

1. Introduce the principle, difference and application of anti shake and throttling, and implement it with JavaScript

If it is triggered continuously within a certain period of time, it will not be called repeatedly. When it is executed after a certain period of time, it is mainly used in the input box. When you need to query something, continuous input will not request the interface

function debounce(fn, delay) {
    let timer = null
    return function (...args) {
        clearTimeout(timer)
        timer = setTimeout(() => {
            fn.apply(this, args)
        }, delay)
    }
}

Throttling means that it is not triggered all the time, but once at a certain time. It is often used to control the sliding and scrolling or the change of window size

function throttle(fn, delay) {
    let start = +Date.now()
    let timer = null
    return function(...args) {
        const now = +Date.now()
        if (now - start >= delay) {
            clearTimeout(timer)
            timer = null
            fn.apply(this, args)
            start = now
        } else if (!timer){
            timer = setTimeout(() => {
                fn.apply(this, args)
            }, delay)
        }
    }
}
2. Implement simple eventemiter, including event binding, event triggering and removal
class EventEmiter {
    constructor() {
        this.events = {}
    }
    emit(event, ...args) {
        this.events[event].forEach(fn => {
            fn.apply(this, args)
        })
    }
    on(event, fn) {
        if (this.events[event]) {
            this.events[event].push(fn)
        } else {
            this.events[event] = [fn]
        }
    }
    remove(event) {
        delete this.events[event]
    }
}

const eventHub = new EventEmiter()

eventHub.on('test', data => {
    console.log(data)
})

eventHub.emit('test', 1)
console.log(2)
3. Merge two ordered arrays

Power button question 88:https://leetcode-cn.com/probl…Just use the merge steps in merge sort

function merge(left, right) {
    let i = 0
    let j = 0
    const temp = []
    while(i < left.length && j < right.length) {
        if (left[i] < right[j]) {
            temp.push(left[i])
            i++
        } else {
            temp.push(right[j])
            j++
        }
    }
    while(i < left.length) {
        temp.push(left[i])
        i++
    }
    while(j < right.length) {
        temp.push(right[j])
        j++
    }
    return temp
}
4. Climbing stairs

Answer question 70:https://leetcode-cn.com/probl…F (x) = f (x − 1) + F (x − 2)

var climbStairs = function(n) {
    if (n <= 2) return n
    let n1 = 1
    let n2 = 2
    let nn = 0
    for (let i = 3; i <= n; i++) {
        nn = n1 + n2
        n1 = n2
        n2 = nn
    }
    return nn
};
5. Monkeys eat bananas

LCQ 875:https://leetcode-cn.com/probl…

function minEatingSpeed(piles, H) {
    let left = 1;
    let right = Math.max(...piles);
    const canEat = (piles, speed, H) => {
        let sumTime = 0;
        for (let pile of piles) {
            sumTime += Math.ceil(pile / speed);
        }
        return sumTime <= H;
    };
    while (left < right) {
        let mid = Math.floor((right + left) / 2);
        if (canEat(piles, mid, H)) {
            right = mid;
        } else {
            left = mid + 1;
        }
    }
    return right;
};
6. LRU algorithm

Topic 146:https://leetcode-cn.com/probl…I like to ask when I test the keep alive algorithm

class LRU {
    constructor(max) {
        this.max = max
        this.cache = new Map()
    }
    get(key) {
        const { cache } = this
        const value = cache.get(key)
        if (!value) return -1
        cache.delete(key)
        cache.set(key, value)
        return value
    }
    set(key, value) {
        const { cache, max } = this
        if (cache.has(key)) {
            cache.delete(key)
        }
        if (cache.size === max) {
            cache.delete(cache.keys().next().value)
        }
        cache.set(key, value)
    }
}
7. Binary tree traversal

There are many ways to traverse the binary tree, such as preorder, middle order, postorder and hierarchical traversal. All of them have the original problem, and generally use recursion or breadth first search

//Preorder traversal
function preorderTraversal(root) {
    const result = []
    function preOrderTraverseNode(node) {
        if (node) {
            result.push(node.val)
            preOrderTraverseNode(node.left)
            preOrderTraverseNode(node.right)
        }
    }

    preOrderTraverseNode(root)

    return result
};
//Level traversal
function levelOrder(root) {
    const res = []
    function dfs(node, step) {
        if (node) {
            if (res[step]) {
                res[step].push(node.val)
            } else {
                res[step] = [node.val]
            }
            dfs(node.left, step + 1)
            dfs(node.right, step + 1)
        }
    }
    dfs(root, 0)
    return res
}

Interview summary of Shanghai Lilis, MIHA tour, B station, little red book, dewu and other Internet companies

8. Palindrome substring

No. 647:https://leetcode-cn.com/probl…

function countSubstrings(s) {
    const n = s.length;
    let ans = 0;
    for (let i = 0; i < 2 * n - 1; ++i) {
        let l = i / 2, r = i / 2 + i % 2;
        while (l >= 0 && r < n && s.charAt(l) == s.charAt(r)) {
            --l;
            ++r;
            ++ans;
        }
    }
    return ans;
};
9. The best time to buy and sell stocks

Power button question 121:https://leetcode-cn.com/probl…

function maxProfit(prices) {
    const len = prices.length
    if (len < 2) return 0
    let min = prices[0]

    let dis = 0
    for (let i = 1; i < len; i++) {
        if (prices[i] < min) {
            min = prices[i]
        }
        const disc = prices[i] - min
        if (disc > dis) {
            dis = disc
        }
    }
    return dis
};
10. Promise all and allseleted
Promise.all = function(promises) {
    const values = []
    let count = 0
    return new Promise((resolve, reject) => {
        promises.forEach((promise, index) => {
            Promise.resolve(promise).then(res => {
                count++
                values[index] = res
                if (count === promises.length) {
                    resolve(values)
                }
            }, err => {
                reject(err)
            })
        })
    })
}

Promise.allSeleted = function(promises) {
    let count = 0
    let result = []
    return new Promise((resolve, reject) => {
        promises.forEach((promise, index) => {
            Promise.resolve(promise).then(res => {
                result[index] = {
                    value: res,
                    reason: null,
                }
            }, err => {
                result[index] = {
                    value: null,
                    reason: err,
                }
            }).finally(() => {
                count++
                if (count === promises.length) {
                    resolve(result)
                }
            })
        })
    })
}
11. Implement maxrequest, resolve the result after success, and try again after failure, and reject after more than a certain number of attempts
function maxRequest(fn, maxNum) {
    return new Promise((resolve, reject) => {
        if (maxNum === 0) {
            reject('max request number')
            return
        }
        Promise.resolve(fn()).then(value => {
            resolve(value)
        }).catch(() => {
            return maxRequest(fn, maxNum - 1)
        })
    })
}

Interview summary of Shanghai Lilis, MIHA tour, B station, little red book, dewu and other Internet companies

Welcome to the official account:Front end recitationShare front-end knowledge together

Recommended Today

New JavaScript syntax “double question mark syntax” and “optional chain syntax”

Double question mark grammar Double question mark grammarThe concept is to return the value on the right when the value on the left is null or undefined let Form = undefined ?? true; //Form = true Alternative chain syntax ? optional chain //Optional chain let body = { value: { a: ‘123321’ } } let […]