Home > Web Front-end > JS Tutorial > A complete collection of selected Web front-end interview questions and answers in 2023 (Collection)

A complete collection of selected Web front-end interview questions and answers in 2023 (Collection)

青灯夜游
Release: 2022-12-15 20:07:02
forward
7705 people have browsed it

This article summarizes some selected Web front-end interview questions worth collecting (with answers). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

A complete collection of selected Web front-end interview questions and answers in 2023 (Collection)

HTML, CSS related


1. What are the most commonly used image formats on the Internet

JPEG, GIF, PNG,The most popular is the jpeg format, which can compress the file to the minimum Provides 11 compression level# when storing in jpeg format ##2. Please briefly describe the css box model

##a

cssA complete collection of selected Web front-end interview questions and answers in 2023 (Collection)

The box can be divided into four parts from the outside to the inside:

margin (margin), border (border), padding (padding), content (content). By default, the width and height properties of the box are simply set to content( Content) width and height, The real width of the box should be: content width

Padding left and right

Left and right margins Left and left bordersThe real height of the box should be: content height

Top and bottom padding

Top and bottom margin Top and bottom border##3. Video /Use of audio tagVideo:

Video tag attribute: src

The video address that needs to be played

width/height Set the width and height of the video to be played, which is the same as the width and height attributes of the img

tagautoplay Whether to play automatically

controls Whether to display the control bar

poster The previously displayed booth picture is not played

loop Whether to loop playback

perload Preload video (cache) and autoplay

conflicts. If the autoplay attribute is set, the perload attribute will be invalid. muted Silent Mode

Audio: The audio attributes are similar to the video attributes, but the width, height and poster attributes cannot be used

4.What are the new contents of HTML5

New semantic tags

New form types

Form elements

Form attributes

Form events

Multimedia tags

5.Html5 new semantic tags What are the advantages of

semantic tags: 1.Improve accessibility 2.seo 3.Clear structure, easy to maintain

HeaderPage header mainMain content of the page footerBottom of page

NavNavigation bar asidesidebar articleLoad a piece of independent content on the page

Section is equivalent to p figureLoad independent content (words below the picture above) figcaption figure's title

HgroupTitle combination tag markHighlight dialog Load dialog label (must match the open attribute)

EmbedLoad the tag of the plug-in videoLoad the video audioLoad audio (supported formats ogg, mp3, wav)

6. New features of Css3

Border:

  • border -radios Add rounded border       

  • ##border-shadow: Add a shadow to the box (horizontal displacement, vertical displacement, blur radius, shadow size, shadow color, insetr(inner/outer shadow))

  • border-image:Set the border image

  • border-image -source The path of the border image

  • border-image-slice The image border is offset inward

  • border-image-width The width of the image border

  • ##border- image-outset

    The amount of the border image area beyond the border

  • border-image-repeat Whether the image border is tiled (repeattiled roundcovered stretch stretch)

Background:

  • Background-size Background image size

  • ##Background-originProvisionsbackground-positionThe property is positioned relative to what position

  • Background-clip Specify the drawing area of ​​the background (padding-box, border-box, content-box)

Gradient:

  • ##Linear-gradient

    ()Linear gradient

  • Radial-gradient

    ()Radial gradient

Text effects:

  • Word-break

    : Define how to break lines

  • Word-wrap

    : Allow long content to be automatically wrapped

  • ##Text-overflow
  • : Specify what should be done when the text overflows the element containing it

  • Text-shadow
  • : Text shadow (horizontal displacement, vertical Displacement, blur radius, shadow color)

  • Transform:

    Transform
  • Apply to 2D3DTransformation, you can rotate, scale, move, and tilt elements

  • Transform- origin
  • You can change the position of the element transformation, (change the xyz axis)

    ##Transform -style
  • Specify how nested elements are rendered in three-dimensional space

    2D
Conversion method:

rotate
  • rotate

    translatex , y) specifies the displacement of the element in two-dimensional space scalen ) Define scaling transformation ##3D

  • Conversion method:

Perspective

    (
  • n) to 3Dtranslate translate rotate scale Transition:

Transition-proprety

    Transition property name
  • Transition-duration The time it takes to complete the transition effect

  • Transition-timing- function Specify the speed of the switching effect

  • Transition-delay Specify when to start switching the effect

Animation: animation

  • ##Animation-name is @keyframesAnimation name

  • animation-duration The time the animation takes

  • animation-timing-function How animation completes a cycle

  • animation-delay Delay interval before animation starts

  • animation-iteration-count Number of animation playbacks

  • animation-direction Whether to play the animation in reverse in turn

##7. What are the ways to clear floats? Please tell us the advantages of each.

Height collapse:

When all child elements float and the parent element does not set a height, the parent element will appear. High collapse.

Clear floating method

1: Define the height of the parent element separately

  • Advantages: Fast and simple, less code

  • Disadvantages: Unable to perform responsive layout

Clear floating method

2: Parent definitionoverflow:hidden ;zoom1(compatible with ie6)

  • Advantages: simple and fast, less code, high compatibility

  • Disadvantages: excess parts are hidden , pay attention when laying out

Clear floating method

3: Add an empty label after the floating element,clearbothheight0overflowhidden

  • Advantages: simple and fast, code Less, higher compatibility

  • Disadvantages: adding empty tags is not conducive to page optimization

Clear floating method

4: Parent definitionoverflow:auto

  • Advantages: simple, less code, good compatibility

  • Disadvantages: internal width and height exceed parent

    When p, a scroll bar will appear

Clear floating method5: Universal clearing method:

  • Add pseudo-objects to collapsed elements

##

.father:after{
         Content:“随便写”;
         Clear:both;
         display:block;
         Height:0;
         Overflow:hidden;
         Visibility:hidden
}
Copy after login
  • Advantages: Fixed writing method, High compatibility

  • Disadvantages: lots of code

8. The positioned attribute values ​​are What's the difference?

Position has four attribute values: relative absolute fixed static

  • ##Relative

    Relative positioning Do not break away from the document flow, position relative to itself

  • Absolute

    Absolute positioning, out of the document flow Relative to the parent positioning

  • ##Fixed
  • Fixed positioning, out of the document flow Document flow, positioned relative to the browser window

  • Static
  • Default value, the element appears in the normal flow

  • 9. How to center the child element in the parent element

Horizontal centering:

1 .

The width of the child and parent elements is fixed, and the child elements are set to margin:auto, and the child elements cannot be set to float. , otherwise the centering will fail2.

The width of the child and parent elements is fixed, and the parent element is settext-align:center, child elements set display: inline-block, and child elements cannot Set floating, otherwise the centering will fail Horizontal and vertical centering:

    The child element is absolutely positioned relative to the parent element, and the child element is positioned absolutely relative to the parent element. Element
  • top, left set 50%, child element margin-top and margin-left minus half of their respective width and height

  • The child element is absolutely positioned relative to the parent element. The top, bottom, left and right of the child element are all
  • 0, and then set the child element margin:auto

  • Parent element settings
  • displaytable-cell vertical-alignmiddle, child element settingsmarginauto

  • The child elements are relatively positioned, the child elements are
  • top, left The value is 50%, transform: translate(-50%-50%

  • The child element is absolutely positioned relative to the parent element, the child element top, left value For 50%, transform:translate( -50%-50%

  • The parent element sets the flexible box,

displayflex justfy-contentcenter align-itemcenter; justfy-contentcenter

##10.The difference between border-box and content-box

Content-box Standard box model widthexcluding padding and border

Border-box Weird Box Modelwidthincludes paddingandborder

11. Element vertically centered

1.Set the row height of the child element to be the same as the parent element

2.Set the child element to an inline block and add vertical-align middle

##3.

Known parent element height, relative positioning of child elements, through transformtranslateY-50%

4.

I don’t know the height of the parent element, the child has no parent element, the child element top:50%,transformtranslateY-50%

5.

Create a hidden node so that its height is half of the remaining height

6.

To the parent element display: table, child element displaytable-cellvertical-alignmiddle

7.

Add a pseudo element to the parent element

8.Flex box, parent elementdisplayflex, child elementalign-selfcenter

12. How to make the chrome browser display text smaller than 12px

Originally added Google private attributes -webkit-text-size-adjust:none, now-webkit-transformscale()

13.What are the Css selectors? , which attributes can be inherited, and how to calculate the priority? What are the new pseudo-classes in Css3

Css2 Selector:

Element selector, idSelector, group selector, class selector, *Wildcard selector, descendant selector

Css2Pseudo class selector: a:link/visited/hover/active

Css3Select Selector:

##Space > Adjacent sibling selector ~Universal selector (Find all following)

Structure pseudo-class selector:

Find which numbernth-childn

Find the number of the same typenth-of-type

Find unique type only-of-type

Attribute selector: Find based on tag attributes [attr=value]

: root Find root elementhtmltag

: empty Check Zhao empty tag

Target pseudo-class selector: (form)

  • ##:

    enabled Find tags that can be used

  • disabled Find prohibited tags

  • checked Find selected tags

Pseudo element selector

::selectionSet the highlighting of selected text content ( Can only be used for background color and text color)

Negative pseudo-class selector

not()

Language pseudo-class selector

lang(value)##Priority (weight):

    Element selector
  • 1

  • Pseudo element selector1

  • ##classSelector 10

  • Pseudo-class selector10

  • Attribute Selector10

  • IdSelector100

  • Inline style weight 1000

  • Contains selector weight is the sum of weights

  • The inherited style weight is 0

Those properties can be inherited:

  • CssThe inherited properties are mainly text aspects

  • All elements inherit: visibility and cursor

  • blocks Level elements can inherit: text-indent and text-align

  • list elements Inheritable: list-style, list-style-type, list-style-position, list-style-image

  • Inline elements are inheritable: letter-spacing,word-spacing,line-height,color,font,font-family,font-size

  • Font-style,font-variant,font-weight ,text-decoration,text-transform,direction

  • Letter spacing Paragraph spacing Line height Font color Font type Font size Font style Font weight Small caps text Text modification Convert text in different elements Text Direction

14. There are a large number of images on the webpage that load very slowly. How can you optimize them?

1.The image is loaded lazily, and a scroll bar event is added to the unvisible area of ​​the image to determine the distance between the image position and the top of the browser and the page. If the former Xiaoyu, the latter, loads first

2.Use image preloading technology to download the previous and next pictures of the current display first

3.Use csssprite or svgsprite

15. What are inline elements/block-level elements?

Inline elements: Adjacent inline elements will be arranged on the same line and will not occupy an exclusive line Set width and height is invalid span

Block-level elements: will occupy one row You can set attributes such as width and heightp

Variable elements: Determine whether the element is a block element or an inline element based on contextual warnings

Block-level elements:p h1-h6 hr p ul ol table address blockquote dir from menu

Inline elements: a br I em img input select span sub sup u textarea

Variable elements: button del iframe ins

16. What is the difference between the standard mode and the weird mode of the browser?

Standard mode: The browser parses and executes code according to W3C standards

Weird mode: The browser parses and executes the code according to its own way. Because different browsers parse and execute the code differently, it is called weird mode

Difference:

  • In weird mode, the box model is the weird box model and in standard mode it is the standard box model

  • Vertical alignment of image elements

    For inline elements and table-cell elements, in standard modevertical- The default value of the align property is baseline, and in weird mode, the table of the picture in the cell vertical-alignThe default value of the property is bottom, so there will be a few pixels of space at the bottom of the image

  • Font in element

    cssfont## The attributes of # are all inheritable. In weird mode, for the table element, some elements of the font cannot be inherited from other encapsulated elements, especially font-sizeAttribute

  • The size of the inline element

    Standard In mode, non-replaced inline elements cannot be capitalized. In weird mode, defining the width and height of the element will affect the size of the element

  • Percent height of element

    When an element uses percentage height, in standard mode, the height changes depending on the content. In Weird Lost, the percentage is accurately Application

  • Handling of element overflow

    In standard mode,overflowThe default value of the value is visible. In weird mode, this overflow will be treated as an extension box, which is the element's The size is determined by the content. Overflow will not be cropped. The element frame is automatically adjusted to include the overflow content.

17. When are margin and padding used?

MarginOuter margin The distance between one border and another border

Padding Padding The distance between its own margin and its own content

Use margin when you need to add space outside border, when you need to add space outside When adding space inside border, use padding

18. What are the layout attributes of the flexible box? Please briefly describe them?

Flex-direction:The arrangement of sub-elements in the flexible container (the main axis arrangement)

Flex-wrapSet whether the child elements of the flex box wrap when they exceed the parent container

Flex-flow: Yesflex-direction and flex-wrap abbreviation

Align-item: Set the flex box element in Alignment on cross-axis

Align-content: Set row alignment

Justify-content: Set the alignment of the flexible box element on the main axis

19. How to disable labels

AdddisabledAttribute

20.Flex layout principle

is to add to the parent box flex attribute to control the position and arrangement of sub-boxes

21. The difference between Px, rem and em

Px, absolute length unit, pixel px is relative to the monitor screen resolution

em Relative length unit, relative to the font size of the text in the current object

The value of em is not fixed

em will inherit the font size of the parent element (the reference is the font-size of the parent element)

                   All fonts in em are determined relative to the size of the parent element

rem relative to htmlfont-size of the root element

1em=1rem=16px at Add font-size to body: 62.5% This is the original px Divide the value by 10 and add em to get

22. What are the three-layer structures of web pages?

structures (html or xhtmMarkup language) Performance (cssStyle sheet) Behavior (js)

23. Please briefly describe the media inquiry

Media query extends the media attribute, is to set different # according to different media types ##css style to achieve adaptive purposes.

24. Disadvantages of Rem

For example: on a novel website, the smaller the screen of a mobile device, the smaller the text will be if rem is used. It will make it very difficult to read the article

25. Remember a few common compatibility contents in the first stage

26. Vertical and Horizontally centered method

27. Three-column layout method with fixed middle adaptive on both sides

1. marginNegative value method: Both left and right columns float to the left, and the left and right columns adopt negative margin values. The middle column is wrapped by a floating element with a width of 100%

2. Self-floating method: left column Float left, float right column, and put the middle column last

3. Absolute positioning method: The left and right columns adopt absolute positioning and are fixed to the left and right sides of the page respectively. On the side, use the left and right margin values ​​to spread the distance between the main body column in the middle.

4.flex Fixed width left and right Middleflex1

5.Grid layout

6. tableLayout

28.Doctype function

Declare the document type

Javascript related


1.What are the basic data types of Js

StringString ValueNumber Booleanboolean null undefined Object Array

2. How to use Ajax

A complete AJAX request includes five steps:

  • CreateXMLHTTPRequestObject

  • UseopenMethod to create http request and set the request address

xhr.open (get/post,url,async,true (asynchronous), false (synchronous)) often use the first three parameters

  • Set the data to be sent, use send to send the request

  • Register event (give ajaxSet event)

  • Get the response and update the page

3. How to determine whether a data is NaN

NaN Not a number But using typeof the detection is numberType

  • ##Use the definition of NaN Use typeof Determine whether it is the number type and whether it satisfies isnan

  • ##Utilization

    NaN is the only feature that is not equal to any of its own n! ==n

  • Take advantage of the

    provided in ES6 Object.is()Method (determining whether two values ​​are equal) n==nan

4. The difference between null and undefined in Js

is the same: when using

if to judge, both will be converted to false

Difference:

number

The converted value is different number (null) is 0 number (undefined) is NaN

Null

Indicates that a value is defined, but this value is a null value

Undefined

Variable declared but not assigned

5. What is a closure? What are the characteristics? What impact will it have on the page?

Closure can be simply understood as: a function defined inside a function. A closure is formed when one of the inner functions is called outside of the outer function that contains them.

Features:

  • Function nested function.

  • # External parameters and variables can be referenced inside the function.

  • #Parameters and variables will not be recycled by the garbage collection mechanism

    .

Use:

  • Read the variables inside the function;

  • The values ​​of these variables are always kept in memory and will not be automatically cleared after the outer function is called.

Advantages:

    ##Variables reside in memory for a long time;
  • Avoid the pollution of global variables;
  • The existence of private members
  • ;

  • Disadvantages: Will cause memory leaks

6. Common memory leaks in Js:

    Unexpected global variable
  • Forgotten timer or callback function
  • Reference from
  • DOM

  • Closure

7. What is event delegation? How to determine the event source (Event.target Whoever calls it is the event source)

JSIn a high level: event delegation is to use event bubbling and only set a time Handlers can manage all events of a certain type.

Event delegation, called event proxy, is a very common technique for binding events in js. Event delegation is to bind events that originally need to be bound. The response event set in the child element is delegated to the parent element, allowing the parent element to take on the role of event listening. The principle of event delegation is DOMThe event bubbling of the element

8. What is event bubbling?

After an event is triggered, it will be propagated between the child element and the parent element. This propagation is divided into three stages,

Capture Stage (transmitted from the window object to the target node (from outside to inside), this stage will not respond to any events), target stage, (triggered on the target node), bubbling stage (conducted back from the target node to the window object (from inside to outside)), the event delegation / event proxy is to use event risk The bubble mechanism binds the events that the inner layer needs to respond to to the outer layer

9. The difference between local storage and cookies

Cookie means cookies. As the name suggests, cookie is indeed very small, and its size is limited to around 4KB. Its main purpose is to save login information. For example, when you log in to a certain website market, you can see "remember password", this This is usually achieved by storing a piece of data identifying the user's identity in Cookie .

localStorage

localStorage is HTML5 The newly added technology in the standard is not an epoch-making new thing. As early as the IE 6 era, there was something called userData used for local storage, and at that time browser compatibility was considered , a more general solution is to use Flash. Nowadays, localStorage is supported by most browsers. If your website needs to support IE6 , then userData is a good choice as your solution.

sessionStorage

sessionStorage and localStorage The interface is similar, but the life cycle of saving data is different from localStorage . Students who have done back-end development should know the meaning of the word Session . The literal translation is " Session" . And sessionStorage is a front-end concept. It can only save part of the data in the current session, and the data will still exist when the page is refreshed. But when the page is closed, the data in sessionStorage will be cleared.

Similarities and differences between the three

##4KGenerally ##Communicate with the serverEase of use

Features

##Cookie

localStorage

##sessionStorage

Lifetime of data

Generally generated by the server, the expiration time can be set. If

Cookie is generated on the browser side, it will be invalid by default after closing the browser

unless it is cleared. Permanently saved

# is only valid in the current session and will be cleared after closing the page or browser

Storage data size

left and right

5MB

will be carried in the
HTTP

header every time. If you use cookie to save too many The data will cause performance problems

The data is only saved on the client (i.e. the browser) and does not participate in communication with the server

Needs the programmer to encapsulate it himself, the original
Cookie

The interface is not friendly

#The original interface is acceptable, and it can also be re-encapsulated to
Object

and Array have better support

10.ES6 new features

const and let, template string, arrow function, function parameter default value, object and array destructuring, for...of And for...in, classes in ES6

##11. The difference between Let, var and const

VarThe declared variables will be mounted on window, while let and constThe declared variables will not be

VarThe declared variables will have variable promotion, let and constThere is no variable promotion

Under the same scopevarcan be declared Variables with the same name, let and const, cannot

Let and const declarations will form a block-level scope

Lettemporary dead zone

Const Once declared, a value must be assigned, and null cannot be used as a placeholder. It cannot be modified after declaration. If the declaration is a composite type Data, attributes can be modified

12. Please briefly describe the array methods

push() Add from the back Element, the return value is the length of the added array

arr.pop() Delete elements from the back, there can only be one, the return value is deleted Element

arr.shift() Delete the element from the front, and can only delete one element whose return value is deleted

arr.unshift() Add elements from the front, the return value is the length of the added array

arr.splice(i,n) Delete the element starting from i (index value). The return value is the deleted element

arr.concat() Connecting two arrays the return value is the new array after the connection

str.split() Convert the string into an array

arr.sort() Sort the array and return the value It is a sorted array. The default is to sort by the leftmost number, not by number size

arr.reverse() Reverse the array, The return value is the reversed array

arr.slice(start,end) Cut off the array from index value start to index value end, excluding the end index The value, the return value is the cut out array

arr.forEach(callback) Traverse the array, no return Even if there is a return, no value will be returned. And it will affect the original array

arr.map(callback) Map the array (traverse the array), and return a new array.

arr.filter(callback) Filter the array and return an array that meets the requirements

13. How to update Json Add/delete key-value pairs

14. Please briefly describe what object-oriented is

Object-oriented is a kind of thinking, which is based on process-oriented. That is to say, object-oriented is to realize functions through objects, encapsulate functions into objects, and let the objects realize specific details; This idea is to put data as the first priority. This is an optimization of data, which makes the operation more convenient and simplifies the process.

Js itself does not have a class type, but each function has a prototypeAttribute, prototype points to an object. When the function is used as a constructor, prototype plays the role of Similar to the role of class

Object-oriented has three characteristics: encapsulation (hiding the properties and implementation details of the object, and providing public access to the outside world) ),

Inheritance (to improve code reusability, inheritance is the prerequisite for polymorphism), polymorphism (reference variables defined by parent classes or interfaces can point to subclasses or specific implementation classes Instance object)

15. The difference between ordinary functions and constructors

  • The constructor is also an ordinary function. The creation method is the same as that of ordinary functions, but it is customary to capitalize the first letter of the constructor

  • . The calling method is different. Ordinary functions are called directly, and the constructor uses the keyword new to call

  • #When called, a new object will be created inside the constructor, which is an instance. Ordinary functions do not A new object will be created

  • #this inside the constructor points to the instance, and # inside the ordinary function ##this points to the object calling the function (if no object is called, the default is window)

  • The default return value of the constructor is the created object (that is, the instance). The return value of the ordinary function is determined by the return statement

  • The function name of the constructor is the same as the class name

##*****16. Please briefly describe the prototype/prototype chain / (Prototype) Inheritance*****

What is a prototype:

Any object instance has a prototype, also called a prototype object. This prototype The object's built-in attribute _proto_ points to the object pointed to by the prototype of its constructor, that is, any object is created by a constructor, but not every object has a prototype, only methods have prototypes.

What is the prototype chain?

The basic idea of ​​the prototype chain is to use prototypes to let one reference type inherit the properties and methods of another reference type.

We know that each constructor has a prototype object, each prototype object has a pointer to the constructor, and the instance contains an internal pointer to the prototype object.

The core of the prototype chain is the pointer of

_proto_ of the dependent object. When the attribute does not exist, the object is created layer by layer. The constructor, until it reaches Object, there is no _proto_ to point to.

Because

_proto_ is essentially looking for prototype, so we only need to look for this chain prototype on the constructor. Among them, Object.prototype does not have a _proto_ attribute, it == null.

Each constructor has a prototype object. The prototype object contains a pointer to the constructor, and the instance contains a pointer to the inside of the prototype object. We make the prototype object (1) equal to the instance of another prototype object (2),

At this time the prototype object (2) will contain a pointer to the prototype object (1),

Then Let the instance of the prototype object (2) be equal to the prototype object (3). This layer-by-layer progression forms a chain of instances and prototypes. This is the concept of the prototype chain.

Each constructor has a prototype object , the prototype object contains a pointer to the constructor (constructor), and the instance object contains an internal pointer to the prototype object (__proto__). If a prototype object is equal to an instance of another prototype object, the prototype object will contain a pointer to another prototype (__proto__), and the other prototype will also contain a pointer to another constructor (constructor). If another prototype is an instance of another type...this forms a chain of instances and prototypes. Also called prototype chain

Prototypal inheritance is a way of inheritance in js,The prototype chain is the main method to implement inheritance, The basic idea is to use prototypes to let one reference type inherit the properties and methods of another reference type ,

Prototypal inheritance: Using members in the prototype can be combined with other Related objects share this feature and can achieve inheritance. This way of implementing inheritance is called prototypal inheritance.

17. Understanding of Promise

1. What is Promise? What problem do we use Promise to solve?

We all know that Promise means promise, a promise that it will give you a result after a period of time.

Promise is a solution to asynchronous programming, which is more reasonable and powerful than callback function and event.

Syntactically speaking, promise is an object from which asynchronous operation messages can be obtained;

2. promiseThere are three states: pending initial state is also called waiting state, fulfilledsuccess state, rejectedfailure state; once the state changes, It won’t change again. After creating the promise instance, it will be executed immediately.

3. Two characteristics of Promise

1. PromiseThe state of the object is not affected by the outside world

2. Once the state of Promise changes, it will not change again. You can get this result at any time. The state cannot be reversed,

4. Three of Promise Disadvantages

1)Cannot cancelPromise,will be executed immediately once it is created and cannot be canceled midway

2 )If the callback function is not set, PromiseThe error thrown internally will not be reflected to the outside

3)When in pending(waiting) state, it is impossible to know which stage the current progress is, whether it has just started or is about to be completed

promise is used to solve two problems:

1.Callback hell, the code is difficult to maintain, often the first function The output is the input of the second function.

2.promise can support multiple concurrent requests and obtain the data in concurrent requests

This promise can solve the asynchronous problem, but it cannot be said that promise is asynchronous

19. Please briefly describe the usage of async

Async is generation and ## The syntax sugar of #promise, async is the of generator Replace * with async and yiled with await

You must add a async before the function, and a await keyword before the asynchronous operation method, meaning Just wait a moment and then continue after execution. Note: await can only be run in the async function, otherwise an error will be reported

PromiseIf an incorrect result is returned and no exception handling is done, an error will be reported, so use try..catchJust catch the exception

20.. What happens in the process from inputting a URL to the completion of page loading and display on a page?

is divided into 4 steps:

1.

When sending a URL request, regardless of whether the URL is the URL of a Web page or a Web page For each resource URL, the browser will start a thread to handle the request and start a DNS query on the remote DNS server. This allows the browser to obtain the IP address corresponding to the request.

2.

The browser and the remote Web server negotiate through the TCP three-way handshake to establish a TCP/IP connection . The handshake includes a synchronization message, a synchronization-response message and a response message, these three messages are passed between the browser and the server. In this handshake, the client first attempts to establish communication, then the server responds and accepts the client's request, and finally the client sends a message that the request has been accepted.

3. Once the TCP/IP connection is established, the browser will send an HTTP GET request to the remote server through the connection. The remote server finds the resource and returns it using an HTTP response

4. At this point, the web server provides resource services and the client begins downloading the resource.

jQueryRelated knowledge


What is Css preprocessing sass less? Why use them

Sass and less are both cssThe preprocessor is an abstraction layer on css. It is a special syntax that will eventually be compiled into css , less is a dynamic style language that gives css the characteristics of a dynamic language, such as: variables, inheritance , nested. LessCan be run on the client or on the server (requires node)

The difference between .call() and .apply() in Js

apply: Call a method of an object and replace the current one with another object object.

call: Call a method of an object and replace the current object with another object.

As can be seen from the definition, call and apply are both methods of calling an object and replacing the current object with another object. The difference lies in the parameters passed. apply can only have two parameters at most - a new this object and an array argArray. If arg is not an array, an error will be reported

Same. Point:The two methods have exactly the same effect. The function of call and apply is to borrow other people's methods to call, just like calling your own.

The difference: Parameters passed by the method Different

Why does it cause cross-domain/please briefly describe the same-origin policy

The reasons why cross-domain problems occur:

In the front-end and back-end separation mode, the domain names of the front and back ends are inconsistent, and cross-domain access problems will occur. During the request process, if we want to get back the data, it is usually a post/get request, so... cross-domain problems occur

Cross-domain problems come from JavaScript's same-origin policy, that is, only If the protocol host name and port number (if present) are the same, mutual access is allowed. In other words, JavaScript can only access and operate resources in its own domain, but cannot access and operate resources in other domains.

Same-origin policy is a well-known security policy proposed by NetScape. The so-called same origin refers to the same protocol, domain name, and port. For security reasons, the browser only allows interface interaction under this domain name. Client scripts from different sources cannot read or write the other party's resources without explicit authorization.

Please output three ways to reduce page loading time

1. Optimize images

2. Selection of image format (GIF: provides fewer colors and can be used in places where color requirements are not high)

3. Optimize CSS (compress and merge css, such as margin-top, margin-left...)

4. Add after the URL Slash (such as www.campr.com/directory, it will determine what file type or directory this directory is.) cdn hosting

5. Indicates the height and width (if the browser does not find these two parameters, it needs to calculate the size while downloading the image. If there are many images, the browser needs to constantly adjust the page. This not only affects the speed, but also affects the browsing experience.

When the browser knows the height and width parameters, even if the image cannot be displayed temporarily, it will make room for the image on the page, and then continue to load the following content. As a result, the loading time is faster and the browsing experience is better. Okay)

6. Reduce http requests (merge files, merge pictures)

This points to

In JavaScript, this usually points to the function we are executing, or to the object to which the function belongs.

Global this → points to this in the Window

→ points to itself

In the event this → points to the event object

What is jsonp and how does it work? Why is it not real ajax

Jsonp is actually a cross-domain solution.

JsCross-domain request for data is not allowed, but js cross-domain request for js script is possible .

So you can encapsulate the data to be requested into a js statement and make a method call.

Cross-domain request js script can get this script. The js script will be executed immediately after getting it.

You can pass data into the method as a parameter. You can get the data. This solves cross-domain issues.

jsonpPrinciple: (Dynamic creation of script tags, Callback function)

The browser allows src cross-domain requests through the script tag in the js request. You can add the callback method name to the request result and define the method in the request page to obtain it. Data requested across domains.

Why is it not real ajax?

1, the two technologies of ajax and jsonp are called in the same way" They look very similar and have the same purpose, which is to request a URL and then process the data returned by the server. Therefore, frameworks such as jquery and ext encapsulate jsonp as a form of ajax;

2But ajax and jsonp are essentially different things. The core of ajax is to obtain the content of this page through XmlHttpRequest, while the core of jsonp is to dynamically add the <script> tag to call the js script provided by the server. </script>

3. So, in fact, the difference between ajax and jsonp is not whether it is cross-domain. Ajax can also achieve cross-domain through the server proxy, and jsonp itself does not Excludes the acquisition of data in the same domain.

4. Also, jsonp is a method or non-mandatory protocol. Like ajax, it does not necessarily require json format to transmit data. , if you want, you can change the characters, but this is not conducive to jsonp providing public services.

Please master 2 or more ways to remove duplicates from arrays

  • Use indexof() method

  • Use lastindexof() method andindexofThe method is the same indexofmatch from the headlastindexofmatch from the tail

  • ES6#set structure setDo not accept duplicate data

  • Use the sort method to sort the original array first, then compare it with the adjacent one, and if different, store it in the new array

  • Use the filiter and indexof methods

  • Use ES6 ’s set and spread operator

  • Use set and Array.from() method array.from can convert the set structure into an array

  • using splice and double layer loop

  • Use includesmethod

What is deep and shallow copy and how to achieve it?

Deep copy: pointer assignment and content copy,

Shallow copy: just simple pointer assignment

Array shallow copy: If it is an array, you can use some methods of the array to implement it: slice(), concat() returns the characteristics of a new array to implement copy. Use the spread operator spread to implement

Array deep copy: JSON.parse(JSON.stringify()) is not only applicable to arrays but also to the object. Functions, undefined, and symbols cannot be copied.

Why js is a weakly typed language

Weakly typed language implementation is compared to strongly typed language. In strongly typed language, variables There are many types, such as int char float Boolean Sometimes conversion between different types requires forced conversion, while jacascript has only one typevar, when assigning a value to a variable, the type will be automatically determined and converted, so it is a weakly typed language.

How to convert less to css

  • Use node to lessFile generated as cssfile
  • Use webstorm Automatic generation

What are the most commonly used echarts

Charts and chart combinations

What is the difference between a For loop and a map loop?

ForTraverse the object's own and inherit enumerable properties, and also That is to say, which properties on the prototype chain will be included

MapThe method will not detect empty arrays, mapWill return a new array and will not affect the original array

Please write a simple class and inheritance

There are three steps to create a class Type:

  • Use the function and this keywords

  • Prototype method Use prototype and thisKeywords

  • Use object.create() method to construct

There are six types of inheritance:

  • Prototypal inheritance

  • Borrowing constructor inheritance

  • Combined inheritance

  • Prototypal inheritance

  • Parasitic inheritance

  • Parasitic combined inheritance

The difference between synchronous and asynchronous/the difference between blocking and non-blocking

Synchronous (blocking)

Asynchronous (non-blocking)

For example: synchronization, we work together, it’s time to eat, I go I asked you to eat together. You are very busy, so I will sit and wait for you to finish your work before we go to eat together. At work, it’s time to eat. I’ll call you to eat together. You’re very busy, so I’ll eat by myself first. You’ll go to eat after you’re done.

Synchronous (blocking) and asynchronous (non-blocking) these two focus on The status of the program when waiting for the call result

What are redraw and reflow

Reflow: Whenrender tree Part or all of it needs to be rebuilt due to changes in the size, layout, hiding, etc. of the elements. This is called reflow. Requires at least once for each page Reflow is when the page is loaded for the first time. Reflow will definitely occur at this time because render tree

When reflowing, the browser will Invalidate the affected part of the rendering tree and reconstruct this part of the rendering tree. After completing the reflow, the browser will redraw the affected part to the screen. This is redrawing

When some elements in render tree need to update attributes, and these attributes only affect the appearance of the elements, not It will affect the layout and is called redrawing

#What is http? What are the characteristics

http is called Hypertext Transfer Protocol, which is the most widely used network protocol on the Internet

Features: Request-based - response mode Stateless saving No connection

HTTP The difference between the protocol and HTTPS

  • http is the hypertext transfer protocol, and the information is transmitted in clear text, https is a secure ssl decryption transport protocol

  • http and httpsThe connection method is completely different, and the port is also different, http is 80, https is 443

  • ##http The connection is very simple , is stateless. The https protocol is a network protocol built from the ssl http protocol that can perform encrypted transmission and identity authentication. Safer than http protocol

The difference between prototype and inheritance, prototype, call and apply inheritance (the first The parameters are the same, what is the difference in the second one)

apply()Receives two parameters, one is the scope in which the function runs (this), The other is the parameter array.

call()The first parameter of the method is the same as the apply() method, but the parameters passed to the function must be listed.

The difference between arrow functions and ordinary functions

  • The arrow function is an anonymous function and cannot be used as a constructor or used new

  • Arrow functions cannot be bound arguments, use restParameter solution

  • #Arrow function has no prototype attribute

  • The arrow function’s this always points to its context’s this,

  • Arrow functions cannot bind this and will capture this## of the context in which they are located. #Value, as its own thisvalue

What is a js memory leak?

Memory leak refers to a piece of allocated memory that cannot be used or recycled until the browser process ends

Methods to release memory: Assign the value to null

How do you optimize the files and resources of your website?

1, file merging (the purpose is to reduce http requests)

2, files Compression (the purpose is to directly reduce the size of file downloads)

3, use cdn hosting resources

4, use cache

5, gizp compress your js and css files

6, meta tag optimization (title, description, keywords), heading tag optimization, alt optimization 7. Backlinks, website external link optimization

Please briefly describe ajax Execution process and common HTTP status codes

100: This status code tells the client that it should continue to send requests. This temporary response is used to notify the client. Part of the request has been accepted by the server, but the client should continue to send the remaining part of the request. If the request has been completed, the response is ignored, and the server will send a final result to the client after the request is completed

200: This is the most common http status code, indicating that the server has successfully accepted the request and will return the final result requested by the client

202: Indicates that the server has accepted the request, but has not yet processed it, and it is still uncertain whether the request will be processed eventually

204: The server successfully processed the request, but did not return any entity content and may return new header meta information

301: The web page requested by the client has been Move permanently to a new location. When the link changes, a 301 code is returned to tell the client the link change. The client saves the new link and makes a request to the new link. The request result has been returned

404: The request failed. The resource requested by the client was not found or does not exist.

500: The server encountered an unknown error, resulting in the inability to complete the client's current request.

503: The server cannot handle the current request due to temporary server overload or maintenance

Preloading and The difference between lazy loading and when is the appropriate time for preloading? Lazy loading is delayed loading, which waits until certain conditions or requirements are met before loading the corresponding resources.

The main difference between the two is that one loads in advance, and the other loads slowly or even not at all. . Lazy loading can relieve pressure on the server front-end to a certain extent, while preloading will increase the pressure on the server front-end.

Jquery

What are the selectors

1. Basic selector

The basic selector is the most commonly used and simplest selector in jQuery. It finds DOM elements through the element's id, class and tag name.

1, ID selector #id
Description: Match an element based on the given id and return a single element (Note : In the web page, the id name cannot be repeated)
Example: $("#test") Select the element with the id of test

2 , class selector.class
Description: Match elements according to the given class name and return a collection of elements
Example: $(".test") Select all elements with class test

3, element selector element
Description: Match elements according to the given element name , return the element set
Example: $("p") selects all

elements

4,*
Description: Match all elements and return the element set
Example: $("*") selects all elements

5, selector1, selector2,...,selectorN
Description: Merge the elements matched by each selector and return them together, and return the merged element set
Example: $("p,span,p.myClass") selects all elements of

, and

tags whose class is myClass

2. Hierarchical selector

The hierarchical selector obtains specific elements based on hierarchical relationships.

1, descendant selector
Example: $("p span") selects all elements in

The element (note: the descendant selector selects all specified selected elements of the parent element, whether it is a child or a grandchild)

2, Child selector $("parent>child")
Example: $("p>span") selects all elements under the

element (note: child selector Only select child elements directly belonging to the parent element)


3, sibling selector$("prev next")
Description: Select the immediate The next element following the prev element returns the set of elements
Example: $(".one p") selects the next

sibling element set with class one


4、Sibling selector$("prev~siblings")
Description: Select all siblings elements after the prev element and return the element set
Example: $("#two~p") selects the set of all

peer elements after the element with id two

##3. Filter selection Device

1>Basic filter selector
1, :first
Description: Select the first An element, returns a single element
Example: $("p:first") selects the first

element among all

elements


2, :last
Description: Select the last element and return a single element
Example: $("p:last") selection The last

element among all

elements


3, :not(selector)
Description: Remove all elements with Given the elements matched by the selector, return the element collection
Example: $("input:not(.myClass)") selects the elements whose class is not myClass
4, :even
Description: Select all elements whose index is an even number, the index starts from 0, and returns the element set
5 , :odd
Description: Select all elements whose index is an odd number. The index starts from 0 and returns the element set
6, :eq(index)
Description: Select the element whose index is equal to index. The index starts from 0 and returns a single element
7 , :gt(index)
Description: Select elements whose index is greater than index. The index starts from 0 and returns the element set
8, : lt(index)
Description: Select elements whose index is less than index. The index starts from 0 and returns the element set
9, :focus
Description: Select the currently focused element

##2>Content filter selector
1、:contains(text)
Description: Select the element containing text and return the element collection
Example: $(" p:contains('I')") Select elements containing the text "I"
2, :empty
Description: Select not Empty elements that contain child elements or text elements, return element collection
Example: $("p:empty") selects empty

elements that do not contain child elements or text elements (

)
3、:has(selector)
Description: Select the element containing the element matched by the selector Element, returns the element collection
Example: $("p:has(p)") selects the

element containing the

element (

)
4, :parent
Description: Select elements containing child elements or text and return a collection of elements
Example: $("p:parent") selects

elements containing child elements or text elements (

or Text

)

##3>

Visibility filter selector1
, :hidden Description: Select all invisible elements and return the element set
2
, :visibleDescription: Select all visible elements and return the element collection

4>Attribute filter selector (returns element collection)
1、[attribute]
Example: $("p[id]") selects the p element with the id attribute
2、[attribute=value]
Example: $("input[name=text]") selects the input element with the name attribute equal to text
3、[attribute!=value]
Example: $("input[name!=text]") selects input elements with name attributes that are not equal to text
4、[attribute^= value]
Example: $("input[name^=text]") Select the input element whose name attribute starts with text
5, [attribute$=value]
Example: $("input[name$=text]") selects the input element whose name attribute ends with text
6、[attribute*=value]
Example: $("input[name*=text]") Select the input element with name attribute containing text
7、[attribute~=value]
Example: $("input[class~=text]") Select the class attribute separated by spaces Input elements whose value contains text
8, [attribute1][attribute2][attributeN]
Description: Combine multiple attributes to filter selections Device

5>Form object attribute filter selector (returns element collection)
1,: enabled
Description: Select all available elements
2, :disabled
Description: Select all unavailable elements Element
3, :checked
Description: Select all selected elements (radio boxes, check boxes)
Example: $("input:checked") selects all selected elements
4、:selected
Description: Select all selected option elements (drop-down list)
Example: $("select option:selected") Select all selected option elements

Jquery method of inserting nodes

append() Append content to each matching element

appendTo() Append all matching elements to the specified element. In fact, using this method reverses the regular $(A).append(B) operation to append A to B.

prepend() Prepend content inside each matching element

prependTo() Prepend all matching elements to the specified element. In fact, using this method reverses the conventional $(A).prepend(B) operation, that is, instead of prepending B to A, A is prepended to B

after() Insert content after each matching element

insertAfter() Insert all matching elements into behind the specified element. In fact, using this method reverses the conventional $(A).after(B) operation, that is, instead of inserting B after A, A is inserted after B

before() Insert content before each matching element

insertBefore() Insert all matching elements in front of the specified element. In fact, using this method reverses the conventional $(A).before(B) operation, that is, instead of inserting B before A, insert A before B

The difference between function throttling and function anti-shake in Js

Function throttling means that the js method is only executed once within a certain period of time .

Function anti-shake means that when triggered frequently, the code will only be executed once if there is enough idle time

Function throttling is a statement A variable is used as a flag to record whether the current code is executing. If it is executing, cancel the method execution and directly return. If it is idle, trigger the method execution normally

Function anti-shake isrequires a delayer to assist the implementation, delaying the execution of the code that needs to be executed. If the method is triggered multiple times, use the last recorded delayed execution code with cleartimeoutClear it and start again. If the timer is over and there is no way to access the trigger, the code will be executed

Get is different from post

Get is to get data from the server, post is to send data to the server

on the client, get Submit data through url, the data can be seen in url, post method, the data is placed in html header to submit

Security issues

GetThe submitted data can only have a maximum of 1024 bytes, post No restrictions

What is csrf attack

Csrf(Cross-site request forgery) After the user has logged in to the target website, the attacker induces the user to visit an attack page, uses the target website's trust in the user, and uses the user's identity to attack the page to initiate a request for a forged user operation to the target website to achieve the purpose of the attack

JsWrite a deep copy by hand

When to use deep copy/shallow copy

No matter how deep it is, it is needed. When a deep copy occurs, it usually indicates that there is an aggregation relationship. When a shallow copy occurs, it usually indicates that there is an acquaintance relationship.

For example Simple example: When implementing a composite patternComposite Pattern, deep copy is usually implemented

When implementing an observer patternObserver Pattern, you need to implement shallow copy

Vue related


##1.Vue What is the core of

Vue is a set of progressive bottom-up incremental development for building user interfaces TheMVVMframework,vue The core only focuses on the view layer,

Core idea:

Data-driven (the content of the view changes as the data changes)

Componentization (can increase code reusability, maintainability, testability, improve development efficiency, facilitate reuse, and reflect high cohesion and low coupling)

2. Please briefly describe your understanding of vue

Vue is a set of progressive methods for building user interfaces The MVVM# framework is developed incrementally from the bottom up. The core is to focus on the view layer, The core of vue isIn order to solve the data binding problem, in order to develop large-scale single-page applications and componentization,So the core ofvue The idea is data-driven and componentized. Here we also talk about the MVVM idea. The MVVM idea is the model View vm is the bridge connecting v and m , when the model layer data is modified, the VM layer will detect it and notify the view layer to make corresponding modifications

3. Please briefly describe Vue's one-way data flow

The update of the parentprop will flow downward to the child component, every time the parent component is updated , all prop of the child component will be refreshed to the latest value

The data is passed from the parent component to the child component, and can only be bound in one direction It is determined that the data passed by the parent component cannot be directly modified inside the child component (you can use data and computed to solve it)

4. What are the commonly used modifiers in Vue

Modifiers.lazy Triggered after change, the value will only change when the cursor leaves the input input box

##   .number Convert the output string to numbertype

.trim Automatically filter user input The leading and trailing spaces

Event modifier:

.stop Prevent click events from bubbling , equivalent to event.stopPropagation().prevent in native

js Preventing the execution of preset behaviors is equivalent to event.preventDefault()##.capture # in native js

##Use the event capture mode when adding an event listener, that is, whoever has the event modifier will trigger it first.self

will only Trigger events within its own scope, excluding child elements.once

Execute only once

Keyboard Modifier:

.enter Enter key .tab Tab key .escReturn key .space Space bar

.upUp key .down .down Down key .leftBuild left .rightRight key

System modifiers: .ctrl .alt .shift .meta

##5.v-text and {{}}The difference between v-html

{{}} Parses the data into plain text and cannot display the outputhtml

v-html can render outputhtml

v-text Parses the data into plain text and cannot output the real html. The difference from the curly braces is that the double curly braces are not displayed when the page is loaded.

v-text Command:

Function: Manipulate the plain text content in web page elements. {{}} is another way of writing

v-text and {{}}Difference:

v-text and {{}} is equivalent, {{}} is called template interpolation, v-textCall command.

One difference is that when rendering a lot of data, the curly brackets may be displayed, commonly known as screen flashing:

6.Can v-on bind multiple methods?

Yes If you bind multiple events, you can use key-value pairs Event type: event name

                

If the binding is multiple identical events, just separate them with commas

7.Vue loop Key function

KeyThe existence of the value ensures uniqueness,VueWhen executed, the node will be checked. If there is no key value, then vue Check that there is a dom node here, the content will be cleared and a new value will be assigned, if there is If the key value exists, then the new and old nodes will be compared and the two key Whether they are the same, swap positions or delete them

8. What is a computed attribute

Computed properties are used to declaratively describe that a value depends on other values. When the value it depends on changes, it is updatedDOM

When binding data to a computed property in a template, vue will update when any value it depends on causes the computed property to changeDOM

Each computed property consists of a getter and a setter, Trigger getter when reading, trigger setter

9. Advantages and disadvantages of Vue single page

Single pagespa

Advantages: front-end and back-end separation Good user experience 一字 Quick Content changes do not require reloading the entire page

Disadvantages: Not conducive toseo , The initial loading time is long (the browser must load html css js at the beginning, and all page content is included in the main page) , the page complexity has increased, and navigation is unavailable

10.What is Vuex? how to use? Use in that scenario

Vuex is a state management tool developed specifically for vue.js applications Mode, by creating a centralized data storage, facilitates access by all components in the program. Simply put, vuex is vue The state management tool

Vuex has five attributes state getters mutations actions modules

State is the data source storage location, corresponding to the data of the general vue object,stateThe data stored in it is responsive. stateWhen the data changes, the components corresponding to the data will also change Call with this.$store.state.xxx

##Getters It is equivalent to the calculated attribute of store, mainly for filtering the data in state, using this.$ store.getters.xxxCall

Mutations All methods for processing data logic are placed in## In #mutations, when an event is triggered and you want to change the state data, use mutations, use this.$store.commit Call, add a parameter to this method, which is the payload of mutation ( payload

Actions Asynchronously operate data, but through mutation Use this.$store.dispatch to trigger, actions also supports payload

Usage scenarios: Status between components, login status, add to shopping cart, music playback

VuexUsage process:

Download vuex

##Create store and# under src ##index.js

Introducing

vue and vuex, Use vuex , export the instance object

in

main.jsIntroduced in .vue file and used

11.Routing jump method in Vue (declarative/programmatic)

Vue

There are two types of routing jumps, namely declarative and programmatic

Use

jsThe way to jump is called programmatic navigation this.$router.push()

Using

router-link to jump is called declarative router-view Routing exit, the location where the routing template is displayed

  • What is the role of the

    name attribute in routing?

  • Navigate using

    name in router-link Go to the corresponding route

  • and use
  • name to navigate while passing the parameters to the sub-route.
12.Vue cross-domain solution

1.

Background changesheader

2.

Use jq to provide jsonp##3.

Usehttp-proxy-middlewareConfigure the middleware of the proxy server13. Please briefly describe the life cycle of Vue. The life cycle of

vue

is vue The process from instance creation to instance destruction. During this period, 8 hook functions will be called. beforeCreate

(Create instance)created

(Creation completed)、 beforeMount

(Start creating template)

mounted(creation completed),

beforeUpdate(start update)

updated(update completed),

beforeDestroy(destruction started)

destroyed(Destruction completed)

14. The role of Vue life cycle

gives users the ability to add themselves at different stages Opportunity of the code

15. DOM rendering is completed within that life cycle stage

DOMRendering is done in mountedIt has been completed in the cycle

16. Implementation of Vue routing

Front-end routing is updated View but not request the page,

Use the anchor point to complete the switch, the page will not refresh

The official website recommends usingvue -router.jsTo introduce the routing module

  • Define the routing component

  • ##Define the route, use component to map the route component, and use name to navigate to the corresponding route

  • Create router instance and pass in routes configuration

  • Create and mount the root instance

  • Use router-linkSet routing jump

##17. Vue routing mode hash and history, briefly talk

Hash

There is # in the mode address bar, history is not, history## When refreshing in # mode, 404 will appear. You need to configure the background using

JavaScript To assign a value to loaction.hash , change the hash value of URL You can use the

hashchange event to monitor changes in the hash valueHTML5

provides History API to implement URL changes. Among them, the most important API are the following two: history.pushState() and history.repalceState( ). These two API can operate the browser's history without refreshing. The only difference is that the former adds a new historical record, while the latter directly replaces the current historical record. 18. Two ways to pass parameters in Vue routing, params and query methods and their differences

Dynamic routing can also be called route parameter passing, means rendering different content in the same component according to different choices

Usage: query is introduced with path, params is introduced with nameIntroduces , receives parameters are similar, they are this.$route.query.name and this.$route.params.name

urlDisplay on :params is similar to post, query is similar to get, which is a security issue, params It is relatively safer to pass values. query Pass parameters through url and refresh the page. Still there, paramsRefresh the page and it’s gone

19. Several ways of Vue data binding

1.One-way binding Double braces {{}} htmlInner string binding

2.v-bindbinding htmlattribute binding

3.Two-way binding v-model

4.One-time binding v-once Depends on v-model

##20.Vue registers a global component

Vue.componnet("Component name"{Object template

Content of establishment

})

21.What are Vue’s routing hook functions/routing guards

Global guard: beforeEach(to,from,next) and afterEach(to,from

Route exclusive guard: beforeEnter

component Guard within: RouterEnterEnter/update/leave22. How to set up dynamic routing in Vue? What are the ways? How to get the passed data? Dynamic routing can also be called routing parameters. Dynamic routing includes

query and

prramsTwo ways to pass parameters

query is introduced with path, params is introduced with name Introduction, queryUse this.$route.query.name to receive parameters

paramsUse this.$route.params.name to receive parameters

##23. What are the common components in Elementui? Please briefly describe the ones you often use and what are their properties?

ContainerLayout Container

Outer Container

Top bar container

Side Sidebar container

Main content container

Bottom bar container

Dropdown Drop-down menu

Drop-down button

Drop-down menu

Drop-down item

Table Table

Tabs Tag page

Form Form

Pagination Pagination

Message Message prompt

24. How to customize instructions in Vue-cli

25 .What are the instructions in Vue

v-for: Loop arrays, objects, strings, numbers

##v -on

: Bind event listening

v-bind

: Dynamically bind one or more attributes

v-model

: Create two-way binding on form controls or components

v-if v-else v-else-if

Conditional rendering

v-show

Switch the element’s display## based on whether the expression is true or false #v-html

Update elementinnerhtmlv-text

Update element textcontentv-pre

Skip the compilation process of this element and sub-elementsv-clock

This directive remains on the element until the associated instance ends compilationv-once

Renders only once26.How Vue defines a filter

过滤器本质就是一个有参数有返回值的方法

new Vue({
    filters:{
      myCurrency:function(myInput){
        return 处理后的数据
      }
    }
})
Copy after login

使用方法:

{{表达式 | 过滤器}}

过滤器高级用法:可以指定参数,告诉过滤器按照参数进行数据的过滤

27.对vue 中keep-alive的理解

概念:keep-alivevue的内置组件,当它动态包裹组件时,会缓存不活动的组件实例,它自身不会渲染成一个DOM元素也不会出现在父组件链中

作用:在组件切换过程中将状态保留在内存中,防止重复渲染DOM,减少加载时间以及性能消耗,提高用户体验。

生命周期函数:Activatedkeep-alive组件激活时调用,deactivatedkeep-alive组件停用时调用

28.如何让组件中的css在当前组件生效

styled中加上scoped

29.Vue生命周期一共几个阶段

创建  加载   更新   销毁

Beforecreate创建前

Created   创建后

Beforemount   加载前

Mounted 加载后

Beforeupdate 更新前

Updated 更新后

Beforedestroy 销毁前

Destroyed  销毁后

页面第一次加载会触发 beforecreate  created   beforemount   mounted

DOM渲染在mounted周期中就已经完成

30.Mvvm与mvc的区别

Mvc模型视图控制器,视图是可以直接访问模型,所以,视图里面会包含模型信息,mvc关注的是模型不变,所以,在mvc中,模型不依赖视图,但是视图依赖模型

Mvvm 模型  视图  vm  vm是作为模型和视图的桥梁,当模型层数据改变,vm会检测到并通知视图层进行相应的修改

31. Why is the data in the Vue component a function?

Data is a function. Each component instance has its own scope. Each instance is independent of each other and will not affect each other

If it is a reference type (object), when multiple components share one data When source, if one data changes, all component data will change, so use the function to return a copy of the object through return (return a new data), so that each instance They have their own scope and do not affect each other.

32. The principle of Vue two-way binding

VueTwo-way binding is: data changes update the view, the view Change update data

Vue Two-way data binding is achieved through data hijacking and observer mode,

Data hijacking, object.defineproperty Its purpose is: when assigning a value to a property, the program can sense it and control it Changing the attribute value

Observer pattern When the attribute changes, the place where the data is used also changes

33. How to pass values ​​​​from components in Vue

Forward: parent to child The parent component binds the data to be passed to the attribute and sends it to the child component Through PROPS 通过 通过

## This inverse: Zi Chuanfu 子 Pass through This. $ emit (custom event name, data to be sent), the parent component sets a listening event to receive, and then gets the data

Brother: eventbus Central event bus

ThroughVuex

34.Bootstrap principle

The implementation principle of the grid system is to define the container size and divide it equally into 12 parts, (24 copies or 32 copies), then adjust the inner and outer margins, combined with media queries, it becomes a powerful responsive grid system.

For example row col-xs-4

36. What to do if a component is used in multiple projects

37. Please briefly describe the slot

It can be divided into these points. First, what content can be placed in the slot (slot)? Where to put it? What does it do? You can put any content and use it in child components to display the child component template data in the parent component normally.

Named slots and anonymous slots, scope slots, to put it bluntly, are attributes on the component, which can be used within component elements,

Can be used in the parent componentslot-scopeGet data from the child component

38.Watch please give a brief description

WatchThe function is to monitor the change of a value and call the method that needs to be executed due to the change

39.Vant Ui please Briefly describe

Lightweight and reliable mobile terminal Vue Component library

##40 .The difference between calculated properties and watch

Computed watch The difference is computed's caching function. When irrelevant data changes, it will not be recalculated and the value in the cache will be used directly. Computed attributes are used to declaratively describe that a value depends on other values. When the dependent value or variable changes, the calculated attributes also change accordingly,

Watch is monitoring the variables defined in data. When the variable changes, watch# will be triggered. Methods in

##41.mvvmWhat is the framework? What is the difference between it and other frameworks (jquery)? Which scenarios are suitable?

The difference between Mvvm and other frameworks is vueData-driven Pass Data is used to display views instead of node operations

Suitable for scenarios with a lot of data operations

42. The reason why Vue’s first screen loads slowly, How to solve it, how to detect the white screen time, how to solve the white screen problem

The reason why the first screen loads slowly:

First loading The page has a lot of component data that needs to be rendered

Solution:

1.Routing lazy loading component:()=>import(“routing address”)

2.uiFrameloading on demand

3.gzipCompression

White screen Time detection:

? ? ? ?

Solve the white screen problem:

①Use v-text to render data

② Use {{}} syntax to render data, but also use v-cloak directive (used to remain on the element until the end of the associated instance for compilation), where should v-cloak be placed, v- cloak does not need to be added to every tag, just add it to the tag mounted by el

43. In the process of Vue double data binding, how do you notify the other side of the change when the data changes?

Data hijacking and observer mode

Vue Two-way data binding is achieved through data hijacking and observer mode,

data Hijack, object.defineproperty Its purpose is: when assigning a value to a property, the program can sense it, control the effective range of the property value, and change the values ​​of other properties

The purpose of the observer pattern is that when the properties change, the place where the data is used also changes

44.Vuex process

In the vue component, actions# are triggered through dispatch ##Submit the operation to modify the data, and then trigger mutations## through the commit of actions #To modify the data, mutations receives the request from commit and will automatically pass mutate to modify state, and finally store triggers the update of each component that calls it

45. How does Vuex request asynchronous data

1.

First create variables in state

2.

Then call the encapsulated axios in action Request, receive data asynchronously, commitsubmit to mutations##Mutations

Change the state in state and assign the value obtained from action to state46. How to submit action to mutation in Vuex. The

Action

function receives a store with Instances of context objects with the same methods and properties can call context.commit to submit a mutation, or get## through context.state and context.getters #stateandgetters47.The difference between Router and router

1. Router

is an object of

VueRouter, through Vue.use(VueRouter) and VueRouter The constructor gets an instance object of router. This object is a global object, which contains all routes and many key objects and attributes. . 2.route

is a jump routing object. Each route will have a

route object. It is a local object that can obtain the corresponding name, path, params, query, etc.49. What is the State attribute of vuex?

State

is where the data source is stored

The data in State

is responsive Yes, if the data in

state changes, the component corresponding to this data will also change

StatePut the global state and through mapstate gettersMapped to the calculated properties of the current component

50.What is the Getter property of vuex?

Getter can perform calculation operations on state, which is store Computed properties

Gettercan be reused between multiple components

If a state is only in It can be used within a component without getters

51. What is the Mutation feature of vuex?

ChangeThe only way to modify the status in the vuex store is to submit mutation, yes Modify the status in store in the callback function

52. What are the actions characteristics of vuex?

Action is similar to mutation, but the difference is actionWhat is submitted is mutation, which is not a direct change of state, but can include any asynchronous operation

54.vuex advantages

Advantages: Solve the communication of non-parent-child components, reduce the number of ajax requests, some can be directly accessed from stateGet

Disadvantages: Refresh the browser, #state in vuex It will return to the initial state. The solution is vuex-along, which must be implemented with calculated properties and sessionstorage

55.Vue routing lazy loading (loading routes on demand)

56.v-for and v-if priority

First of all, do not use v-if and v-for on the same element, reason: v-for takes precedence over v-if. If you need to traverse the entire array every time, it will affect the speed, especially when it is needed. When rendering a small part.

v-for has a higher priority than v-if

Please write down the 5 components of Ele.me
Pop-up window
Dialogue
Calendar
Progress bar
Switch

React related


##fetch VS ajax VS axios

Traditional Ajax refers to XMLHttpRequest(XHR ), The earliest technology to send back-end requests, belonging to the original js, the core uses XMLHttpRequest Object, if there is a sequence relationship between multiple requests, callback hell will occur. JQuery ajax is an encapsulation of the native XHR

axios is based on Promise , which is essentially an encapsulation of the native XHR, except that it is Promise The implementation version of conforms to the latest ES specification,

fetch is not ## Further encapsulation of #ajax, but native js, without using the XMLHttpRequest object.

React event processing---modify this to point to

method1 : Bind in place through the bind method to change thisPoint to

Way2#: By creating an arrow function

Way3: In constructorBind events in advance

method4 : Change the writing method of event call to the form of arrow function

Please briefly describe your understanding of react

React originated from facebook, react is a used to build user interfaces jsLibrary

##Features:

  • ##Declarative design

    react Using paradigm declaration, developers only need to declare the display content, react will be completed automatically

  • Efficient

    : reactBy pairing ## Simulation of #dom (that is, virtual dom), minimizing the interaction with dom

  • Flexible
  • reactcan work with known libraries Or the framework works well

  • Component: Build the component via react, let The code is easier to reuse and can be well applied in large-scale project development. The page functions are split into small modules Each small module is a component

  • One-way data flow react is a one-way data flow, the data passes through props is passed from the parent node to the child node. If one of the parent's props changes, react will be re- Render all child nodes

Data transfer between react components

Use forward value transfer props

Reverse value transfer and use function to pass value Transfer by calling function through event

Same-level value transfer Use pubsub-js

Use pubsub.publish(event name, data) to throw data

Use pubsub.subscribe(listening event, ()=){}) Receive data

Pass across components Use context To use contextTo transfer values ​​across components, you need to use the createContext() method. This method has two objects provider producer Consumer consumer

The difference between Vue and react

Same points:

  • Both support server rendering

  • There are all virtualdom, component development, passing the parent and child component data through the props parameters, all implementedwebcomponentSpecification

  • are all data-driven views

  • # #All have state management, reacthasredux,vuehasvuex

  • all have solutions that support native' reactreact native vueweex

Difference:

  • ##react

    Strictly only for mvcview layer, vue is mvvmmode

  • Virtualdom is different, vue will track the dependencies of each component , there is no need to re-render the entire dom component tree, unlike react, when the application state is changed, all components will be re-rendered Rendering, so react uses the shouldcomponentupdate life cycle hook function to control

  • Components are written differently , react is jsx and inline style is to write all html and css into js In , vue is html, css ,jsIn the same file

  • ##The data binding is different,vue Realizes two-way data binding, reactThe data flow is one-way

  • In In react, the state object needs to use the setstate method to update the state, in# In ##vue, the state object is not necessary, the data is contained in the data attribute ##vueManagement in object

  • Please briefly describe the virtual dom and diff algorithm

Virtual

DOM is often called a virtual node, which is an object# through js ##The object simulates the nodes in DOM, and then renders them into the real DOM through a specific rendering method node. Frequent operations

DOM

, or a large number of page redraws and reflows Diff

algorithm: Decompose the tree structure hierarchically, compare only elements at the same level, and add a unique

key value to each unit of the list structure to facilitate comparison. Your understanding of components

Combinable, reusable, maintainable, testable

What happens after calling setState?

React

After calling

setstate, react will Merge the incoming parameter object and the current state of the component , triggering the reconciliation process,

During the reconciliation process, react will build the react element tree and re-render the entire ## based on the new state #UIInterface, after getting the element tree, react will automatically calculate the difference between the old and new nodes, and minimize and re-render the interface based on the difference.

react Life cycle function

componentWillMount Before the component is rendered Call

componentDidMount Call after the first render

##componentWillReceiveProps

After the component receives Call shouldComponentUpdate when a new props

determines whether the component is updatedhtml

componentWillupdate

Called when the component is about to be updatedhtml

componentDidupdate

Call immediately after the component completes updating

componentWillUnmount

Call before the component is removed

******Why virtual dom will improve performance?(Required exam )

virtual

dom is equivalent to js and The real dom adds a cache in the middle and uses the dom diff algorithm to avoid unnecessary dom Operation, thereby improving performance

(# of the component)State What is the difference between (state) and attributes (props)The difference between State and props

Props

is a parameter passed into the component from the outside. Its main function is to pass data from the parent component to the child component, but propsIt is read-only for the components that use it. Once assigned, it cannot be modified. New props can only be actively passed in through external components to re-render the sub-component

State The display form of a component can be determined by the data state and external parameters. The external parameters are props, and the data state is state, first of all, when initializing the component, use this.state to set an initial state# for the component. ##, this data will be used to render the component when rendering for the first time. state is different from props At one point, state can be modified through this.setState()Method to modify state

shouldComponentUpdate What does it do

Thisreact life cycle hook function is to solve this problem:

Use ## when updating data #setStateModify the entire data. After the data changes, all content will be re-rendered during traversal. A small amount of data is fine, but a large amount of data will seriously affect performance

Solution:

1.shouldcomponentupdate

Determine whether the component is updated before rendering, and then render after it is updated

2.purecomponent

(Pure component) eliminates the process of generating and comparing virtual dom In class components Used in

3.react.memo()

Similar to pure components Used in stateless components

react diff Principle

It is based on three strategies:

  • tree diff web UI

    domThere are very few cross-level node movement operations and can be ignored

  • component diff

    Two components with the same class will generate similar tree structures, and two components with different classes will generate different tree structures

  • element diff

    For a group of child nodes at the same level, they can pass a unique idDistinguish

What is a controlled component

React

The component responsible for rendering the form. The value is controlled by state. The input form element is called a controlled component

Call super(props) What is the purpose

Super() calls the constructor method of the parent class, with super, the component has its own this, which is global in the component You can use this, if it is just constructor without executing super, then this are all wrong, super inherits the parent component’s this

How to build components in React

Custom components: functional components or stateless components The first letter of the component is capitalized

Class component: A class component must implement a render method, which must return a jsxElement, use an outer element to wrap all content

Mini program related


Advantages of small programs

No need to download and install, use it directly, run quickly, build the project quickly, short and concise, eachappThe source code does not exceed 2mb

The page composition of the mini program (4 files)

Index .js index.json index.wxml index.wxss

Life cycle of small program

Onload onready onshow onhide onunload

Onpulldownrefresh onreachbottom onshareappmessage

How the mini program requests data

Use request

How to improve the mini program The first screen loading time of the program

Advance request: Asynchronous data data request does not need to wait for the page rendering to complete

Utilize cache: Utilize storage APICache asynchronous request data. When starting the second time, first use the cached data to render the page, and then update the background.

To avoid white screen: first Display the page skeleton and basic content

Timely feedback: Give timely feedback on interactive operations that require users to wait, to avoid users thinking that the mini program is not responding

Performance Optimization: Avoid improper use of setdata and onpagescroll

Please briefly describe the small files you often use Components of the program

View icon text image swiper navigator input button map

Please briefly describe the difference between Wxss and css

WxssAdded new size units rpx

Provides global styles and local styles

WxssOnly supports somecssSelector id' class Elements, etc.

How to implement responsiveness in mini programs

Rpx

How to optimize mini programs

Improve page loading speed

User behavior prediction

Reduce the size of the default data

Componentized solution

Independently learn your own server

How to display user avatars in mini programs With username

Traditional interfacewx.getuserinfo It is currently available and requires user authorization. There will be an official prompt when using it. This method needs to be upgraded

The latest method: open-data tag, use this tag to directly obtain the avatar and user name without user authorization,

You can write opendata as an attribute in button, write a click event and get it directly

Please talk about the similarities and differences between the two-way binding of the mini program and vue?

Vue Two-way binding is through data interception and observer mode, through this.value To get the value, the applet triggers the binding of form elements. In the method, use this.setData({key:value}) to get the value

How to pass parameters in the applet

andvue Introduction by analogy

Let’s talk about the adaptation issues of WeChat mini programs

What are the ways to transfer data between mini program pages? method?

How do you encapsulate the data request of the WeChat applet

Tell me about the adaptation problem of the WeChat applet

How to jump to a page from a mini program

How to jump to another mini program from a WeChat mini program

Solution to the slow loading of the mini program

Others


What is Typescript? Please briefly describe it?

What are the advantages of Typescript and javascript?

The difference between Webpack and gulp

Gulp is a tool that can optimize the front-end development process, webpack is a modular solution grunt

Please describe briefly The difference between loaders and plugins in webpack

What is loaders,loaders is The file loader can load resource files and process these files, such as compilation, compression, etc., and finally package them into specified files.

What is plugin, there will be many events in the life cycle of webpack ,plugincan monitor these events

Difference: The loader is used to load files, webpack itself can only load jsfiles(Built-inbabel-loader), to load other files you need to install other loader , for example: css-loader file-loader

Plugin is an extension of webpack function Yes, through plugin , webpack can realize complex functions that loader cannot complete

How to improve page performance? What are the performance optimizations?

What Node is used for

Can run on the server sideJavaScript

Webpack: Entry, exit, loader, plug-in

Let’s talk about the packaging principle of webpack

Webpack treats the project as a whole. By giving a main file, webpack will be found starting from this main file. All dependent files in the project are processed using the loaders class, and finally packaged into one or more browser-recognizable js files

Commonjs ES6Differences in modules?

  • commonThe module is a copy, the value can be modified, es6The module is a reference, Read-only status, the value cannot be modified

  • commonjsThe module is loaded at runtime,es6Module is the compile-time output interface

How to use Git/What are the common instructions

What technology do you use in the backend

You Why do you still use Vue Family Bucket for a relatively small project?

Please briefly describe the UI framework you use in the project

The more ways to optimize front-end performance, the better

What is cors

Talk about your understanding of websocked

Websocked is a Two-way communication protocol, after establishing a connection, websocked The server and the browser can actively send or receive data to each other, websockedrequired Similar to tcp, the client and server are connected through a handshake. Only after the connection is successful can they communicate with each other.

The data passed in the background is those

Talk about the difference between Ajax, fetch, axios

Project process in the enterprise


1.WEB front-end project development process

Project requirements Analysis

This link is completed by the project manager. The project manager first communicates with the customer to understand the customer's needs, and then analyzes the feasibility of the project. If the project can be realized, the project manager writes out the project requirements. The document is handed over to the designer to complete subsequent development.

Page design/Project selection

This link mainly involves the participation of UI designers. The UI designers analyze documents based on product requirements and design the overall art style, interaction design, interface structure, operation process, etc. of the product. Responsible for the design and production of various interactive interfaces, icons, LOGOs, buttons and other related elements in the project. And make sure to use technology

coding

This part is implemented by programmers. (Programmers are divided into WEB front-end development engineers and back-end development engineers. Front-end developers mainly do the pages that we can see on the web page, while the back-end does some management systems and function implementations that we cannot see.) Programmers work on the UI according to the The designer's design uses coding to complete various functions of the entire project.

Testing

This part is completed by the program tester. Program testers mainly test and find bugs that still exist in the program. Generally speaking, there are problems with the programs that have just been coded. Testers need to test repeatedly and hand over the problematic test results to the coders to fix the bugs. . When almost all bug fixes are completed, the project is almost ready to go online.

Maintenance

Program maintenance is the last stage of the entire project, but it is also the most time-consuming and costly. Program maintenance includes subsequent bug fixes and program version updates after the program is launched.

2. Change the interface domain name

The background interface called during development is the interface for background testing. After the project goes online, the requested interface must be replaced with the online domain name

3. Frequently used tools

Code management platform: github code cloud

Requirements release platform: DingTalk task, ZenTao

Ui interaction platform: Blue Lake

Product prototype tool: axure

Enterprise email: Alibaba Tencent enterprise email

Backend language: java php python (not many in Xi'an)

4. Large companies and small companies Differences in company development

Large outsourcing companies are more process-oriented, have more personnel, and less communication. They do not need to maintain the project themselves after delivery, and adopt the waterfall development model (based on documents)

Small companies: There are few people, frequent changes, communication convenience, and agile development (quickly launch v1 version, and then iterate)

5. How to test the separation of front and backend?

Weird question


What do you use for back-end development?

How to refresh the page on mobile?

Project initialization and construction process

What are you proud of in the project?

Talk about your shortcomings

What is hot deployment?

How many users are there

How to call the interface (how to communicate with the backend)

How to do cell testing

How do you handle the environment variables of the development environment, test environment, and online environment during development?

For more programming-related knowledge, please visit: Programming video! !

The above is the detailed content of A complete collection of selected Web front-end interview questions and answers in 2023 (Collection). For more information, please follow other related articles on the PHP Chinese website!

source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template