One of the summary of front-end interview questions (selected 10 questions)

CSS+HTML

1. H5New features

  • Canvas -- element for painting
  • video, audio -- media for playing video and audio.
  • Semantic tags: header nav main article section aside footer
  • webSocket -- A protocol for full-duplex communication over a single TCP connection.
  • localStorage, sessionStorage -- local offline storage.
  • New form controls -- such as: date, time, email, url, search.

2. Redraw & rearrange

  • Reflow (reflow) : When the DOM changes, causing geometric changes such as the shape and size of the element, the browser will recalculate the geometric attributes of the element and place it in the correct position. This process is called reflow.
  • Redrawing : When the appearance of an element changes without causing a change in layout, the process of redrawing the element is called redrawing

3.BFC

Official: The block-level formatting context is part of the visual rendering of a web page, CSSthe area where the layout process of the block box takes place, and the area where floating elements interact with other elements. BFCThe restriction rules for browser pairs are

  • The child elements of the generated BFCelement are placed one after the other.
  • Vertically their starting point is the top of a containing block, and the vertical distance between two adjacent child elements depends on the element's margin property. The margins of adjacent block-level elements in BFC-- will collapse (Mastering margin collapsing).
  • In the child elements of the generating BFCelement, the left margin of each child element touches the left border of the containing block (for right-to-left formatting, the right margin touches the right border), even for floating elements (although the child element's The content area is compressed due to the float), unless the child element also creates a new one BFC(e.g. itself is a floated element). Triggering conditions:
  • the root element, the HTMLlabel
  • float element: floatthe value isleft、right
  • overflowThe value is not  visible, for  auto, scroll,hidden
  • displayValues ​​are  inline-block, table-cell, table-caption, table, inline-table, flex, inline-flex, grid,inline-grid
  • Positioning element: positionthe value is absolute、fixed

My understanding:  the inner boxes will be placed one after the other in the vertical direction; the box spacing in the vertical direction is determined, but two boxes marginbelonging to the same one will overlap; the left and right margins of each box will not exceed the block containing him ; The area of ​​​​will not overlap with the area of ​​​​the element; floating elements are also counted when calculating height;BFCmarginBFCfloat

  • Solve the overlapping problem: add an exploit rule marginto one of the boxes ( the area of ​​​​will not overlap with the area of ​​​​the element)floatBFCfloat
  • Use BFCto clear the float: floating elements are also counted when calculating the height, so you can use this to clear the float

4. How to optimize CSS rendering performance when writing CSS code?

  • Inline the key Css above the fold, and load the main content first.
  • Load CSS asynchronously
//设置link标签media属性为noexis,浏览器会认为当前样式表不适用当前类型,会在不阻塞页面渲染的情况下再进行下载。加载完成后,将media的值设为screen或all,从而让浏览器开始解析CSS
<link rel="stylesheet" href="mystyles.css" media="noexist" onload="this.media='all'">
//通过rel属性将link元素标记为alternate可选样式表,也能实现浏览器异步加载。同样别忘了加载完成之后,将rel设回stylesheet
<link rel="alternate stylesheet" href="mystyles.css" onload="this.rel='stylesheet'">
复制代码
  • Use selectors wisely

5. What are CSS responsive layouts?

  • CSS3 media query @media query (troublesome, there are many situations to consider, not recommended)
  • Adding "name="viewport meta tag"" to the header meta tag means that the width of the web page is equal to the screen width by default
  • With the help of raster in bootstrap
  • Flexbox (recommended)

6. CSS box model (standard box model and IE box model)

Common ground: Both box models are composed  content + padding + border + margin of and their size is  content + padding + border determined by, but the calculation range of the box content width/height (ie  width/height) varies depending on the box model:

  • Standard Box Model: Contains only  content .
  • IE Box Model: content + padding + border .

box-sizing  changes the box model of an element:

  • box-sizing: content-box : Standard box model (default).
  • box-sizing: border-box : IE (alternative) box model.

JSrelated

1. Closure (interview + written test === high frequency)

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

  • Advantages: extend the life cycle of variables, privatize variables
  • Disadvantages: The variables of the function will always be kept in memory, and too many closures may lead to memory leaks
 function fun1() {
      let n = 0;
      function fun2() {
        n++;
        console.log("@"+n);
        return n
      }
      return fun2;
    }
    let res = fun1();
    // 执行12次,fn2中的变量的生命周期变长了,fun2函数中的n被外部使用了
    for (let i = 0; i < 12; i++) {
      console.log(res()+"执行的第"+(i+1)+"次");
    }
复制代码

2. Prototype, prototype chain (high frequency)

  • Prototype chain : When we access the property of an object, if the property does not exist in the object, then it will go to its prototype object to find this property, and the prototype object will have its own prototype, so we keep looking for it. Go down, this is the prototype chain. 

  • The end of the prototype chain is generally Object.prototypeso that's why our newly created objects can use the toString()etc method. Object.prototype.toString.call([])//tostring可以返回一个精确的类型
  • Prototype : In  JS , whenever an object (function) is defined, some predefined properties are included in the object. Each of these 函数对象has an prototype attribute that points to the function's原型对象

3. thisPoint to

  • In the global function, this points to the window
  • as a method call of an object this points to the calling object
  • In the custom constructor, this points to the new instantiated object (new will change the point of this)
  • In event binding, this points to the event source
  • This points to window in the timer function

4. JSWhat are the ways of inheritance?

  • Prototype chain inheritance
  • Borrowing constructors to implement inheritance
  • composition inheritance
  • ES6Inheritance using extendsand keywordssuper

5. JS event loop mechanism or js execution mechanism?

Understand the Event Loop at a time

EventLoop, like a bank calling system, responsible for finding the function in the corresponding task queue, and then putting it into the execution stack for calling. The task queue is divided into macro tasks and micro tasks. During the execution process, after a macro task is executed, check whether there is a micro task, if not, execute the next macro task, and so on until all execution ends.

js is a single-threaded, asynchronous, non-blocking I/O model, and an execution mechanism for event loop event loops

All tasks can be divided into two types, one is synchronous task (synchronous) and the other is asynchronous task (asynchronous). A synchronous task refers to a task queued for execution on the main thread, and the latter task can only be executed after the execution of the former task is completed. Asynchronous tasks refer to tasks that do not enter the main thread but enter the "task queue" (task queue). Only when the "task queue" notifies the main thread that an asynchronous task can be executed, the task will enter the main thread for execution.

Macro task contains

script(整体代码)
setTimeout
setInterval
I/O
UI交互事件
postMessage
MessageChannel
setImmediate(Node.js 环境)
复制代码

microtasks

Promise.then
Object.observe
MutationObserver
process.nextTick(Node.js 环境)
复制代码

Please write the output of the following code (js event loop mechanism)

new Promise(resolve => {
	console.log(1);
	setTimeout(() => console.log(2), 0)
	Promise.resolve().then(() => console.log(3)) 
    resolve();
}).then(() => console.log(4)) 
console.log(5)
复制代码

1 5 3 4 2

6, native ajax

ajaxIt is an asynchronous communication method that obtains data from the server and achieves the effect of partially refreshing the page.

Implementation steps :

  • Create XMLHttpRequest object;
  • Call the open method to pass in three parameters request mode (GET/POST), url, synchronous and asynchronous (true/false);
  • Listen to the onreadystatechange event, and return responseText when readystate is equal to 4;
  • Call the send method to pass parameters.

7. Event bubbling, delegation (capture)

  • Event bubbling refers to triggering a certain type of event on an object. If the object is bound to the event, the event will be triggered. If not, it will be propagated to the parent object of the object, and finally the parent object will trigger the event.

  • Event delegation essentially exploits the mechanism of browser event bubbling. Because the event will be uploaded to the parent node during the bubbling process, and the parent node can obtain the target node through the event object, so a listener function can be defined on the parent node, and we can go to the element that triggers the event, and the parent node will monitor it. The function handles the events of multiple child elements uniformly, which is called event delegation.

    event.stopPropagation() 或者 ie下的方法 event.cancelBubble = true; //阻止事件冒泡

8. Promises? (high frequency)

It is a solution to asynchronous programming. It can be thought that it is a container, which stores the results of things that will end in the future. At the same time, Promise is also an object from which messages of asynchronous operations can be obtained. It can solve the problem of nested callbacks.

How many states can promises have? three

  • promiseThere are three states pending (waiting), completed (fullled), rejected (rejected)
  • A promisestate can only be changed from " 等待" to " 完成" or " 拒绝", and cannot be reversed. At the same time, "Complete" and "Reject" states cannot be converted to each other.

What are the methods of promise?

  • promise.all-----When multiple asynchronous operations occur at the same time, wait for the end of the last one to end. As long as there is an error, you can't get it
const request1 => () => axios.get()
const request2 => () => axios.get()
const request3 => () => axios.get()
const request4 => () => axios.get()
Promise.all([request1(), request2(), request3(), request4()]).then(res => {
    // res中就包含了四个请求得到的结果
})
复制代码
  • promise.race----- It can happen at the same time when multiple asynchronous operations occur at the same time. The first one ends in some asynchronous processing. If we want to set the timeout time, the xhr object can call xhr.abort() to end the request. but no other
const asyncFn = () => new Promise(() => {
    // 代码
})
Promise.race([asyncFn(), new Promise((resolve) => {
    setTimeout(() => {
	    resolve()    
    }, 5000)
})])
复制代码
  • Promise.reject (returns a failed promise)
  • Promise.resolve (returns a successful promise)
  • Promise.prototype.finally (finally executes regardless of success or failure)
  • Promise.prototype.catch (that is, calling the then method of the promise itself, only passing in the failed callback)

Async and await

  • sync/await is syntactic sugar for generator functions async/await is implemented based on promises, they cannot be used for ordinary function callbacks. async/await is more in line with synchronous semantics and makes asynchronous code look more like synchronous code. async/await is the same as promise, It is a non-blocking execution of async functions that return promise objects

9. Function anti-shake and throttling (high frequency - written test + interview)

Function anti-shake: execute the code multiple times within the specified time, and only execute the last time (when the button is clicked frequently, only the last time will take effect) Function throttling: define an execution frequency time, and execute it every corresponding frequency time during the execution process Once (when inputting content in form validation, scroll bar event)

Usually in the project we will directly use lodashthe library to solve the corresponding problem

// 防抖
function debounce(func, wait) {
    let timeout;
    return function () {
        let context = this;
        let args = arguments;
        if (timeout) clearTimeout(timeout);
          timeout = setTimeout(() => {
            func.apply(context, args)
        }, wait);
    }
}

// 节流函数
function throttle(fn, delay) {
    // 记录上一次函数触发的时间
    var lastTime = 0;
    return function() {
        // 记录当前函数触发的时间
        var nowTime = Date.now();
        if (nowTime - lastTime > delay) {
        // 修正this指向问题
            fn.call(this);
        // 同步时间
          lastTime = nowTime;
        }
    }
}
document.onscroll = throttle(function() { console.log('scroll事件触发' + Date.now()) }, 200)

复制代码

10, let; const; var difference?

difference:

Scope:

  • Variables declared by Var can only be global or function blocks.
  • The scope of a variable declared by let can be either global or the entire function block
  • var allows duplicate declarations in the same scope, while let does not allow duplicate declarations in the same scope, otherwise an exception will be thrown
  • var declaring a variable in the global environment will create a new property in the global object, while let declaring a variable in the global environment will not create a new property in the global object.
  • var declares a variable with variable promotion; let declares a variable with a temporary dead zone

Same point:

  • The scoping rules for var and let are the same, and the variables they declare are only available in the block or subblock in which they are declared

 Summarize and recommend a practical interview question bank for everyone

 1. Front-end interview question bank ( required for interview) Recommended: ★★★★★            

Address: Front-end interview question bank

2. Recommended front-end technology navigation      : ★★★★★

Address: Front-end Technology Navigation Daquan

3. Recommended color value conversion tools for developers    : ★★★★★

Address: Developer Color Value Conversion Tool

Guess you like

Origin blog.csdn.net/weixin_42981560/article/details/126407051