Home>Article>Web Front-end> Summarize some common front-end interview questions (with answers) to help you consolidate your knowledge!

Summarize some common front-end interview questions (with answers) to help you consolidate your knowledge!

青灯夜游
青灯夜游 forward
2022-07-29 09:49:53 2337browse

Summarize some common front-end interview questions (with answers) to help you consolidate your knowledge!

The main purpose of publishing articles is to consolidate my knowledge and become more proficient. It is all based on my own understanding and the information I searched online. If there is something wrong, I hope you can give me some advice. Below are some common interview questions I have summarized. In order to urge myself, I will continue to update

js part

1. Tell me about you Understanding of the prototype chain

In the js language, each instance object has a__proto__attribute, which points to its prototype object, and the constructor of this instance object There is a prototype attributeprototype, which points to the same object as the __proto__ attribute of the instance object. When the object is looking for the value of an attribute, if it does not have one, it will refer to his ## based on __proto__. #PrototypeSearch on the prototype object. If it does not exist, it will search on the prototype object of the constructor that generated the instance object. If it still does not exist, it will continue to search on the prototype object of Object. If it searches upward, it will be null. , this chain search process is calledPrototype Chain.

2. The relationship between prototype, constructor and instance object

Let’s start with the constructor, which points to it through

prototypeThe prototype object refers back to this constructor through itsconstructorattribute, indicating which constructor the prototype object was generated by. The prototype object is an instance object generated by the new keyword. This instance object can point to the prototype object of the constructor that generated the instance object through the__proto__attribute, realizing a triangular relationship.

Summarize some common front-end interview questions (with answers) to help you consolidate your knowledge!

#3. Ways to implement inheritance

There are many ways to inherit, and there are many answers on the Internet. I will summarize it myself. And roughly speaking, there are these five types

1) Prototype chain inheritance

With the help of prototypes, objects can be created based on existing objects, and there is no need to create your own. Define type. Inside the object() function, a temporary constructor is first created, then the passed in object is used as the prototype of the constructor, and finally a new instance of this temporary type is returned. Key code:

Star.proyotype = new Person(), Star.proyotype.constructor = StarDisadvantage: Only the methods of the parent class can be inherited

2) Borrowing constructor inheritance

Call the supertype constructor inside the subclass constructor. Constructors can be executed on newly created objects by using the

apply()andcall()methods. Key code:Person.call(this,age,name)Disadvantage: cannot be reused, can only inherit the attributes of the parent class

3) Combined inheritance

Also called pseudo-classical inheritance. It refers to combining the techniques of prototype chaining and borrowing constructors to take advantage of the best of both worlds. Use the prototype chain to inherit prototype properties and methods, and borrow constructors to inherit instance properties. It not only realizes function reuse by defining methods on the prototype, but also ensures that each instance has its own attributes. But there will be a small bug. There are two copies of age and name, and the value of one is undefined, because the

apply()andcall()methods will automatically Called once.

4) Parasitic combination inheritance

Inherit properties by borrowing constructors, and inherit methods through the mixed form of the prototype chain. Essentially, you use parasitic inheritance to inherit from the supertype's prototype and then assign the result to the subtype's prototype. It is recognized as a comprehensive method of inheritance. If you want to write it all, it is still very much. I only know a simple one?, the key code:

Star.prototype = Object.create(Person.prototype)

5) ES6’s Class class inheritance method

You can use the class keyword together with the extends keyword to achieve inheritance. The class keyword was introduced in ES6 to declare a class, and class (class) can inherit the properties and methods of the parent class through

extends,superpoints to the prototype object of the parent class, and can be called The attributes and methods of the parent class, and the super keyword must be in the constructor method of the subclass and must appear before this.

4. js data types

Data types are generally divided into two types

    Basic data types: String, Number, Boolean, Null, Undefined, Symbol(nbs)
  • Complex data types: Object, Array, Function
  • Symbol represents a unique value to avoid attribute name conflicts

5. Detect data type

  • typeofDetect existing problems: null or the array is printed as object

  • instanceof(Only complex data types can be detected)
    The return value is true or false As long as the relevant constructor is on the prototype chain, it is true, otherwise it is false. It can be used to detect whether it is an array

  • ##Object.prototype.toString.call(Required Detected data value)Why do you need to borrow Object.prototype.toString? Because your toString has been rewritten by your own prototype and you cannot get something like [object Object]

6. How to detect that a data is an array
var arr = [2, 3, 4] console.log(arr instanceof Array) console.log(Array.isArray(arr)) console.log(Object.prototype.toString.call(arr))

7. Deep copy and shallow copy

  • Shallow copy: just copy one Layer-by-layer, only the address is copied at the deeper object level

  • Deep copy: Layer-by-layer copy, the data at each level will be copied

  • Shallow Copy method:

    1. Use lodash shallow copy
    clonemethod, let them point to different addresses2. Use
    Object.assignmethod3. Use es6 Grammar
    ...Extension operator

  • Deep copy method:

    1. Use
    JSON.parse(JSON.stringify(obj)), Disadvantage: When the object has methods and undefined properties, they will be lost2. Use
    recursion

      If there is a
    • cyclic referenceStack overflow will appear
    • Solution idea: Save the processed objects. When processing new objects, you will look in this storage place to see if they have been processed properly. If Just return it directly
let obj = { name: "zs", age: 20, father: [2, 3, 4], }; function deepClone(target) { //这一行如果不用三元判断 如果是数组会有bug会被拷贝成伪数组对象 let tempObj = Array.isArray(target) ? [] : {}; for (let key in target) { if (typeof target[key] === "object") { tempObj[key] = deepClone(target[key]); } else { tempObj[key] = target[key]; } } return tempObj; } let obj1 = deepClone(obj); console.log(obj1);

8. The difference between slice and splice

    Both are
  • Method of array deletion
1.splice changes the original array, slice does not change the original array.

2.slice will return a new array, which can be used to intercept the array.
3.In addition to deletion, splice can also be replaced and added to the array.
4.splice can pass in 3 parameters, slice Accepts 2 parameters

9, the difference between substr and substring

  • The function of both is to intercept the string

    The

  • substr is to extract a string of specified length starting from the starting index number
  • substring is to extract two specified index numbers in the string The characters between
10. The difference between let const var

let and const are both used to

declare variables

, in ES5 we can use var to declare variables -Use let and const functions- Prevent classic scenarios of variable promotion in for loops-
Do not pollute global variables

var keyword declares variables

1. The variable declared by the var keyword exists,

The problem of variable promotion

;2. The variable declared by var does not existBlock-level scope
, if so Global variables can be called anywhere;3. If the name of the var declaration variable is repeated, the later declaration will overwrite the previous declaration;

let key sub-declaration variable

1.

No variable promotion

, there is no variable promotion problem when let declares a variable: if the variable is called before let declares the variable, an error will be reported (prompt that the variable cannot be accessed before initialization) ;2.Block-level scope
, let declares that variables exist in block-level scope (global, function, eval strict mode), which only takes effect in the current code block. If it is outside the current code block The call will report an error (the current variable is not defined);3.Does not affect the operation of the scope chain
4.Does not allow repeated declaration of variables
, let declaration Variables are not allowed to be declared repeatedly. If the same name is declared repeatedly, an error will be reported (the current identifier has already been declared);

const declaration of variables

1. Variables declared by const also have the following characteristics:

No variable promotion

,block-level scope,repeated declarationis not allowed;2.const The declared variables are allconstants
(amounts that are not allowed to change). Once declared, they are not allowed to be modified. If modified, an error will be reported - constant variable assignment3. Generally, in third-party frameworks, Extensive use of const to declare variables can prevent users from modifying variables in the framework;4. What const actually guarantees is not that the value of the variable cannot be changed, but that the data stored in the memory address pointed to by the variable cannot be changed. For simple types of data (numeric values, strings, Boolean values), the value is stored at the
memory address
pointed to by the variable, so it is equivalent to a constant.

11. The process of new

    Creates a new empty object. (i.e. instance object)
  • Let this point to this new object
  • Execute the code in the constructor and add properties and methods to this new object
  • Return this new object obj. (The return value is not written in the defined constructor.)
12. Anti-shake throttling

Anti-shake

  • 防抖是指在事件触发n秒后再执行,如果在n秒内再次被触发,则重新计算时间。(就是在触发某个事件后,在下一次触发之前,中间的间隔时间如果超过设置的时间才会发送请求,一直触发就不会发送请求 应用场景:
    a、scroll事件滚动触发,
    b、搜索框输入查询
    c、表单验证
    d、按钮提交事件
    e、浏览器窗口缩放,resize事件
function debounce(func, delay) { let timer = null // 计时器 return function (...args) { clearTimeout(timer) // 清除上一次计时器 timer = setTimeout(() => { // 重新定时 func.apply(this, args) }, delay) } }

节流

  • 节流是指如果持续触发某个事件,则每隔n秒执行一次。
function throtte(func, time) { let timer = null // 计时器 return function (...args) { if (timer) return // 无视,直接返回 timer = setTimeout(() => { func.apply(this, args) }, time) } }

13、promise的3种状态

这点简单介绍概念,用法后面在详细介绍

1) . 初始态pending

- pending。它的意思是 "待定的,将发生的",相当于是一个初始状态。创建[Promise]对象时,且没有调用resolve或者是reject方法,相当于是初始状态。这个初始状态会随着你调用resolve,或者是reject函数而切换到另一种状态。

2 ). 成功态resolved--也叫fulfilled

- resolved。表示解决了,就是说这个承诺实现了。 要实现从pending到resolved的转变,需要在 创建Promise对象时,在函数体中调用了resolve方法(即第一个参数)。

3) . 失败态rejected

- rejected。拒绝,失败。表示这个承诺没有做到,失败了。要实现从pending到rejected的转换,只需要在创建Promise对象时,调用reject函数。

14、冒泡排序

// 上口诀 双层for循环 外层长度-1 内层长度-1-i let arr = [4, 3, 1, 7, 8, 10] for (let i = 0; i arr[j + 1]) { let temp = arr[j] arr[j] = arr[j + 1] arr[j + 1] = temp } } } console.log(arr)

Vue部分

1、MVVM

MVVM是三个单词的缩写,model(数据,一般来自ajax或本地存储)+view(视图template)+viewmodel(vue实例)

  • model数据变了,视图会跟着改变,如果用的是v-model,数据也会跟着改变,viewmodel在中间起一个桥梁作用
  • model 和 view 就像现实中房东和租客一样,他们是不认识的,通过中介 viewmodel
    好处
    • 数据驱动
      • 因为数据变了。视图也会跟着变,所以在 vue 中不用操作dom来改变视图
    • 解耦(降低了耦合性)
      • 由于 model 和 view 是没有关系的,是通过 viewmodel 结合在一起的,所以维护起来很方便,因为 model 逻辑代买改了,view 不用改

2、vue生命周期

  • vue中的生命周期是指组件从创建到销毁的过程,主要分为4个周期8个钩子函数

1.分别是创建阶段的beforeCreatecreated,一般在beforeCreate写loading加载效果,使用户体验更好,一般在created中发送ajax请求获取数据

2.然后是挂载阶段的beforeMountmounted,一般会在mounted中操作DOM元素

3.更新阶段的是beforeUpdateupdated,当数据更新时需要做统一的业务处理时,拿到最新的dom,可以使用updated 这个钩子函数

4.最后是销毁阶段的beforeDestroydestroyed,可以在beforeDestroy做一些清理的工作,比如说定时器 和解绑一些addEventListener监听的事件

  • 补充:(还有keep-alive的两个钩子函数,使用场景是当组件切换时会进行销毁,因此组件中的初始化的4个钩子函数会多次执行,比较浪费资源,此时可以使用keep-alive纪行组件的缓存,可以让组件切换时不被销毁,keep-alive有两个独有的钩子函数,分别是activateddeactivated,是组件激活和失活时会执行的两个钩子函数)

3、单向数据流

单向数据流是指父组件向子组件传递数据,子组件通过props接收,当父组件中的值改变了,子组件中对应的数据也会改变,因为props是只读的,所以无法直接在子组件中对父组件传递过来的值进行修改,但是如果这个数据是一个引用数据类型,是可以直接在子组件中修改数据中的某个属性的,只要不改变这个数据的内存地址就可以

4、双向数据绑定

  • 数据 -> 视图
  • 视图 -> 数据

vue中普通指令都可以实现数据变了,视图会跟着变,但是有一个特殊的指令叫v-model,它一般用于表单控件,它可以实现双向数据绑定,所谓的双向数据就是数据变了,视图就会跟着改变,反过来也是

5、v-model原理

v-model一般配合input框使用,实现双向数据绑定的效果,它是v-bindv-on的语法糖,原理是通过v-bind将数据绑定给input框,再通过v-on:input,在input中的值改变时,通过$event可以获取到事件源对象 再通过target.value获取到input中更新后的值 将这个值再赋值给绑定的数据即可

Summarize some common front-end interview questions (with answers) to help you consolidate your knowledge!

6、事件传参

在vue的组件使用自定义事件时,$event代表子组件抛出的数据,当这个自定义事件触发一个方法时, 可以不传$event而且可以在方法中进行接收,但是如果写的话就一定要写成$event的形式,这是一个固定写法, 或者这个方法既要传参又要使用事件对象,这个时候$event也是必须要写的 - @click='fn' 在回调函数直接通过参数可以拿到事件对象 - @click='fn($event)' 这个时候@event是固定写法

7、父子组件的声明周期执行顺序

1.初始化阶段时,先执行父组件的beforeCreatecreatedbeforeMount三个钩子函数,然后执行子组件的beforeCreatecreatedbeforeMountmounted四个钩子函数,最后执行父组件的mounted钩子函数

2.更新阶段,先执行父组件的beforeUpdate,然后执行子组件的beforeUpdateupdated,最后执行父组件的updated

3.销毁阶段,先执行父组件的beforeDestroy,然后执行子组件的eforeDestroydestroyed,最后执行父组件的destroyed

8、v-if和v-show的区别

v-ifv-show都可以控制标签,实现组件的显示与隐藏,不同点是v-show是通过display的block和none属性来控制的,当元素隐藏时,页面结构依然存在

  • v-if是通过将元素创建和销毁来控制显示与隐藏的,当v-if的条件为否时,会直接销毁该元素,当满足时会重新创建出来,有可能会影响页面的回流或重绘

  • 如果该元素需要频繁切换时可以使用v-show,不需要频繁切换时可以使用v-if,提高性能

9、v-for和v-if为什么要避免一起使用

  • 因为v-for的优先级比v-if要高,两者同时作用于一个标签或组件时,v-for会优先执行,执行后再进行v-if的判断,但是不满足v-if的条件的时候是可以不执行v-for的,这时候就会造成资源浪费,性能比较差
  • 解决办法是可以通过计算属性将满足v-if判断条件的数据筛选出来,再使用v-if直接渲染筛选后的数据,或者是当v-if不依赖v-for时,可以通过template将v-if写在循环的外部,这样当不满足v-if的判断条件时,就不会再执行v-for了,也可以将数据放在计算属性里面计算过滤出来的数据在交给v-for循环,代替v-if的作用,即可解决。

10、自定义指令:directive

应用场景

  • v-imgerror公司项目中有的用户头像可能加载报错,可以给他一张默认图片, onerror this.img=默认图片

  • v-focus打开带有搜索的页面的时候,实现自动把光标定位到 input 中

  • 自定义指令的钩子函数

1.bind属性绑定的时候执行 只会有一次
2.inserted当前指令所在的元素插入到页面中的时候执行一次
3.update当前指令所在的组件中的 data 数据有更新就会执行,可以执行多次

// 指令的钩子有三个 bind inserted update // bind inserted 只会执行一次 // update 会反复执行 Vue.directive('focus', { inserted(el) { el.focus() }, }) Vue.directive('red', { bind(el) { el.style.color = 'red' }, }) Vue.directive('check', { update(el) { const reg = /^[a-zA-Z0-9]+$/ if (reg.test(el.value)) { el.style.color = 'green' } else { el.style.color = 'red' } }, })

浏览器的缓存机制

这块部分理解不是很透彻,大家浅看一下就可以了?

  • Concept: The browser will store the requested resource as an offline resource. When the resource is needed next time, the browser will decide to use the cached resource directly or send a request to the server again based on the caching mechanism
    Function:
  • Reduces the transmission of unnecessary data and reduces the pressure on the server
  • Speeds up client access speed
  • Enhance user experience
  1. Strong cache: Use local offline resources before expiration and will not interact with the server
    • http1.0 expire specific time January 1, 2023
    • http1 .1 cache-control time period 1 year (high priority)
  2. The essence of negotiation cache is to see whether local things and the server have become old (whether there are updated resources on the server) Strong cache It will not interact with the server to negotiate. The cache will interact once to determine whether things have become old.
    • http1.0 last-modified/if-modified-since
    • http1.1 etag/if-none- match (high priority)
  • There is an img in the current page, and its src is logo.png
    1. First check if there are any local cache resources , if not, you need to send a request to the server to get the resource back at the same timeexpire,cache-control,last-modified,etag(In response message)
    2. After a period of time (uncertain), there is another page with an img and the src is also logo.png. At this time, check to see if there are any cached resources locally. , if found, take a look atexpire,catch-control(if there is, the priority is to look atcache-control), if it is not expired, use That's fine (this piece belongs to strong cache). But if it is found that it has expired, it will start to enter the cache negotiation stage, and send a request to the server toif-modified-since(the value islast-modifieded)/if-none-match(etag)After the request is sent, the server starts to compare to see if the resources on the server are newer than the local ones. If the server resources are still old, a status is returned. The code is 304. When the browser sees that the status is 304, it will continue to use local offline resources. If the server resource has updated resources, the status code is 200, and the server needs to pass a new logo.png to the browser, and the process is repeated.

Design Pattern

My technology stack is mainly front-end vue, so I still lack knowledge in this area, so I will try my best to explain it clearly. , in fact, I don’t understand it very well. I roughly understand that if you want to fully understand it, you still need a lot of technical reserves. Obviously I am not one, haha?

1. Observer mode

The observer pattern means that an object is dependent on multiple objects. When the dependent object is updated, all dependent objects will be automatically notified.

  • The observer pattern is defined A one-to-many dependency relationship between objects. When the state of an object changes, all objects that depend on it will be notified and automatically updated.
    Metaphor:
    Baby-> Parents, grandparents One-to-many dependency relationship
    Baby Cry-> Parents and grandparents rush over to serve. When the status of an object changes, all objects that depend on it will be notified and automatically updated

  • Mode features: There aretwo subjectsOne is the observedDepThe other is the observerwatcher, in vuev- bandadopts this model concept. The disadvantage is that the coupling is too high

2. Publish-subscribe model

Publish-subscribe model In fact, it is a one-to-many dependency relationship between objects. When the state of an object changes, all objects that depend on it will be notified of the state change.

  • In the current publish-subscribe model, the message sender called the publisher does not send messages directly to the subscribers, which means that the publisher and the subscriber do not know each other’s exist. There is a third component between the publisher and the subscriber, called the dispatch center or event bus, which maintains the connection between the publisher and the subscriber, filters all incoming messages from the publisher and responds accordingly Distribute them to subscribers

  • Mode features: There arethree subjectsPublisher dispatch center subscribers, reflected in vueeventBusThis model concept can achieve decoupling

3. The difference between the two models

  • The number of subjects is different. The observer mode has two subjects, namely the observedDepand the observerwatcher. The publish and subscribe model has three subjects, namely the publisher dispatching center (event channel) and the subscriber

  • Compared with the observer mode, the publish-subscribe mode has one more event channel. The event channel serves as a dispatch center to manage the subscription and publishing of events, completely isolating the dependence between the subscriber and the publisher. Subscribers and publishers are decoupled (not aware of each other's existence)

(Learning video sharing:Web front-end introduction,jQuery video tutorial)

The above is the detailed content of Summarize some common front-end interview questions (with answers) to help you consolidate your knowledge!. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete