1. Tell the difference between cookie,sessionStorage and localStorage
Cookie: created on the server side, saved on the browser side, request to carry the corresponding cookie, the length and quantity are limited (4K)
LocalStorage: getItem persistent storage that persists after the browser is closed
SessionStorage: sessionStorage that disappears after closing the browser
Methods: the getItem (), setItem (), removeItem (), the valueOf (), the clear (), hasOwnProperty ()
2. State what you know about the HTTP status code
1XX (information) : Indicates that the request has been received and processing continues
100: The client must continue to make requests
2xx: indicates that the action is received successfully
201: created, the request succeeded and the server created a new resource. 202: accepted, the server accepted the request but has not yet processed it
3XX (Redirect class) : In order to complete the specified action, further processing must be received
301: The requested page has been permanently moved to a new location 302: Temporary redirection 303: Temporary redirection and always request a new URL using GET 304: The requested page has not been modified since the last request
4XX (Client error class) : Request contains incorrect syntax or does not execute correctly
400: The server cannot understand the format of the request, and there is a high probability that the request will be passed. 401: The request is not authorized. 403: Access forbidden
5XX (Server error class) : The server cannot execute a correct request correctly
500: Most common server-side error 503: Server gas temporarily unable to process requests (possibly overload or maintenance)
3. Common array methods
Array.from() : Converts an array-like object or convenience object into a real Array
Array. The prototype. CopyWithin () : shallow copy part of an Array to another location in the same Array, and returns it, won’t change the length of the original Array
Array.prototype.some() : tests that at least one element in the Array passes the provided function test. This returns a Boolean value, true/false
Array.prototype.every() : Tests all elements of an Array
Array.prototype.flat() : Unroll layers of nested arrays to return a new Array
Array.prototype.includes() : Determines whether an Array contains a specified value, returning true if it does, false otherwise
Array. Proyotype. LastIndexOf () : returns the last of the specified element in the Array index, if there is no return 1, look ahead of the back of the Array Array. The prototype, the reduce () : Execute a reduce function (ascending) that you provide for each element in the array, summarizing its results into a single return value
Array.prototype.entries() : Returns a new Array Iterator containing the key-value pairs for each index in the Array
Filter () : Creates an array containing all the elements that pass the function test
Find () : Returns the first element in an array that satisfies the test function provided
Arr.pop () : Pops an element from the end of the array and returns the popped element
Arr.push () : Pushes an element from the end of the array and returns the new length of the array
Arr.shift () : Pops an element from the head of the array and returns it
Arr.unshift () : Pushes an element from the head of the array
Arr.concat ([arr]) : Concatenates the elements of the original array and passes the parameters to form a new array and returns it without affecting the original array
Arr. Join (‘-‘) : Concatenates array elements into strings, accepts a concatenate string, and returns a string
Arr.slice () : copies a portion of the array. Parameters: Get the start and end index of the array
Arr.splice () : Insert or delete elements in the array. This will affect the index position of the data to be deleted until the end of the array
4. Describe the CSS box model
It is divided into standard box model and IE box model
Standard: the content + padding + border + margin
IE: Content + Margin Adds padding+border to content
5. Why cross-domain problems exist and how to solve them
The reason is the same origin policy adopted by the browser for security
If the protocol, domain name, and port number are the same, they are from the same source. If they are different, they are from different sources
1.JSPON solves cross-domain problems
How it works: Because Script tags are not affected by the browser’s same-origin policy, allowing resources to be used across domains, you can create script tags dynamically and then cross domains using the SRC attribute, which is the basic principle behind using JSPON cross-domains
2. Use CORS to solve cross-domain problems
‘Acces-Control-allow-origin -‘ * ‘
3. Configure the forward proxy
Principle: Forward proxies mainly proxy is the client, reverse proxies generally use nGINx
6. Route Guard (Navigation Guard)
Routing guard is some hooks, in the process of routing hop routing jump is a big process, after this big before the process is divided into jump, and so on small process, also in each process function, this function allows you to operate some other things, this is the routing guards, similar to the hook function component life cycle.
Global front-guard: router.beforeeach
Global resolution guard: router. BeforeResolve
Global post-hook: router.aftereach
Exclusive guard for routing: beforeEnter
Guard within component: beforeRouterEnter
beoreRouteUpdate
beforeRouteLeave
7. Function throttling and anti-shaking
Throttling: Set a specific time, but the function is executed only once in a specific period of time, not frequently
For example: in the game, when the mouse is held down, bullets do not line up in a straight line
Requirement: Print once every one second while scrolling the wheel with the mouse
Shake: delay the action to be executed. If it is triggered again within the delayed period of time, the previous action will be cancelled and the timer will be reset
Requirement: when searching, send query request after user complete input content
8. Wechat mini program
Wechat applet does not have DOM, everything is based on componentization
Its configuration scheme is 1rpx=0.5px
A maximum of 1 MB of data can be stored in a single key, and all data can be stored at a maximum of 10MB. Otherwise, the memory will overflow
Applets do not need to register routes. They access the global configuration Pages list and need to specify API hops
The event handling of applets is mainly divided into bubbling event bind+ time name and non-bubbling event Catch + event name
Wx.request () is the syntax for sending requests. It is important to note that the protocol is HTTP. For each interface (current applet), a maximum of 20 domain names can be configured, and the maximum concurrency limit is 10 (the number of requests sent at the same time).
Applets get openId process (unique user id)
The small program client gets the code, sends the request to the developer server, and the server integrates the other two data to the wechat server in exchange for openId
Custom login status encrypts the current data, generates tokens, and returns the tokens to the front end
9. It features
Header Footer nav
New form type: Tel Date
Video and Audio
Canvas drawing
LocalStorage and sessionStorage
10. Mobile adaptation
Scheme 1: ViewPort
Scheme two: REM adaptation
Three ways to achieve REM adaptation
1. Set the size of the root element using media query. The size of the element should be calculated according to the design draft
2. Js dynamically changes the size of the root element and calculates it according to the design draft
3. Dynamic change of JS with CSS preprocessor, namely less
11. How to realize lazy loading of pictures
Definition: When you open a page with many images, load only the images you see on the page and scroll down to the bottom of the page before loading the images you need. This is image lazy loading
Function: Reduces or delays the number of requests, alleviates browser stress, and enhances user experience
Implementation: Set the SRC attribute of the image to the same image, and define a data-src attribute to store the real address of the image
Determine if the image is in view during initial display or browser scrolling
When the image is in view, js automatically changes the SRC property of the image in this area to the real address
12. Data broker in Vue
The object. DefineProperty () method is called to add each attribute of data to the VM instance object. The set and GET methods are reset
13. How does Vue implement bidirectional data binding
Vue implements data binding mainly by means of data hijacking + message subscription publishing mode
Using Object.defineProperty() to hijack attributes in the monitoring data and publish messages to all subscribers when the data changes, each of which updates the corresponding DOM node
Two-way data binding is based on one-way data binding, which gives the element binding input to listen, and saves the latest value to the corresponding attribute once the input changes
14. Closure
Definition: A closure is a reference stored in an inner function to the variable object of the outer function. This reference guarantees that the inner function can access the variable object of the outer function without being disposed of by the garbage object after the outer function completes execution
Function: extend the life cycle of the local variable of the external function, so that the external function can operate the data inside the function indirectly for many times
Disadvantages: Variable permanent internal, will increase the memory usage, improper use is easy to cause memory leaks
15. During the development of Vue project, the corresponding interface does not change when updating the status data. If new attributes are added to the instance after it is created, why does it not trigger view update
Reason: The general method adds a new attribute to an already bound object that has no data binding
Adding a property to a reactive object and ensuring that the property is also reactive and triggers view updates must be used to add new properties to a reactive object, because Vue cannot detect normal new properties
Vue. Set ()
this.$set(this.data,’key’,value)
16. Talk about prototypes and prototype chains
When retrieving a property or method from an object, if the object does not have such a property or method, it will look for the prototype object it is associated with. If the object does not have such a property or method, it will look for the prototype object it is associated with. If not, continue looking for the object referenced by prototype.prototype, and so on, until prototype…… The prototyoe is undefined, forming what’s called a ‘prototype chain’.
17. Difference between arrow function and ordinary function
①. This refers to the problem
The arrow function’s this refers to the parent scope’s this, which is determined by looking up the scope chain. In other words, the context of this refers to the object where it was defined, not the object at which it was used
A normal function points to its direct caller
②. Cannot be used as a constructor
The arguments object does not exist in the function body and can only be used as rest
④ The yield command cannot be used, so arrow functions cannot be used as Generator objects
18. Tell me what you understand about Vuex
Vuex is a plug-in for VUE that centrally manages (read/write) the shared state of multiple components in a VUE application.
State: An object that contains multiple state data. Data written to data in the future can be written to state
Mutations: An object that contains multiple methods for directly modifying state data
Actions: Objects that contain multiple methods for indirectly modifying state data
Getters: Objects that contain get methods that read computed properties of state data
19. Mix (mix)
In vue, if multiple components have the same configuration options, you can extract the same configuration options into a JS file, and then import the object exposed by this file into the configuration options of the component. The mixins:[] method is used to import the object, and the component can use the mixed configuration options content
20. Communication between components
(1) props.
It is usually used for parent to child transmission through tag attributes, and is received by props in child components. It can also be used for cross-component communication and layer by layer transmission. However, it increases the complexity and is prone to problems
Props is a process of assigning a value to the props object. If the data passed contains reference data types, reference passing occurs. Modifying data in a child component will affect the state of the parent component
②. Custom function transfer
This function is used to define functions and declare parameters in the parent component, pass the function to the child component through props, and call the function in the child component with the argument
(3) slots.
Mostly used to pass label data internally to components
Scenario: Encapsulate components for reuse. Extract different labels from components and transfer them to slots to improve component reuse
Category: Common slot, named slot
Normal slots can be used when there is only one slot in a component
A named slot is used when a component has multiple slots based on the name of the slot
④. Event bus
Most commonly used for cross-component communication
Prototype Mounts vUE instance objects to vue prototype objects
Vue.prototype.$Bus = new Vue()
$on(‘ event name ‘, callback function) binds the event
$emit(‘ event name ‘,’ parameter data ‘) emits events
$off(‘ event name ‘) Unbind event
21. Lifecycle of Vue
There are 11 of them, 8 of them are commonly used
beforeCreate
created
beforeMount
mounted
beforeUpdate
updated
beforeDestroy
destroyed
The Active state is used when the Actived component is cached
Deactivated Indicates that the component cache is in the inactive state
ErrorCaptured, called when an error from a descendant component is caught
22. Browser rendering principle analysis
①. First, the rendering engine downloads HTML and generates a DOM Tree by parsing it
When CSS tags or JS script tags are encountered, start a new thread to download them and continue building the DOM
③ The CSS Rule Tree matches the DMO Tree to locate the coordinates and size. This process is called Flow or Layout
(4) The process of drawing web pages by calling Native GUI apis is called Paint
23. Object native methods
Object.isprototypeof () Whether an Object is a prototype of another Object
Object.tostring () defines a string representation of an Object
Object.valueof () specifies the original valueOf the Object
24. The difference between apply,call and bind
I’m changing the this point
Call and apply execute immediately, call being a normal parameter and apply passing an array
Bind returns a new function that will not be executed immediately
25. The way to determine data types
Method 1: typeOf operator
Return value: ‘string ‘,’ number’,’boolen’,’undefined’,’object’,’function’,’symbol
TypeOf NULL returns object, but NULL is not an object
Method two: the instanceof operator
Judge A instaceof B through the prototype chain and search layers in the prototype chain of A to see if there is A prototype equal to B. Prototype
Method 3: Object. The prototype. ToString. Call () method
26. Execution context
What is it: the environment in which the current code is running
Global execution context:
Identify Windows as a global execution context before executing global code
Preprocessing of global data (preparsing) : global variables defined by var, defined in advance (declared), undefined, are added as Windows properties
Function declared global functions, pre-defined (declared), added as Windows methods
This is assigned to this
Function execution context:
When a function is called, its execution context is created before it is ready to execute the function
Start preprocessing local functions
Parameter => Assign an argument => define the parameter in the corresponding execution context area of the function
Arguments => Assign values to a list of arguments defined in the corresponding blame context area of the function
The local variable defined by var => is assigned to undefined and is defined in the corresponding execution context area of the function
The function declared => assignment (function body content) is defined in the execution context of the function
This => Assign (the object on which the function is called)
Execution context stack
Overall code operation steps:
Before the global code runs, the JS engine creates a stack structure to store and manage all execution contexts
② After the global execution context (undefined) is determined, it is added to the stack (push), at this time the bottom of the stack is the global execution context
③ Before the function is executed, create the execution context of the function, and then push the stack
④ After the current function is executed, remove the execution context of the function from the stack (out of the stack).
⑤. When all the code has been executed, only the global execution context is left in the stack
Note: In the execution context stack, the execution context of the current function is always at the top of the stack
27. String methods
CharAt (x) : Returns the character at position X in the string, with subscripts starting at 0
Concat (v1,v2) : Concatenates two or more strings. This method does not alter the existing string, but returns a new concatenated string
IndexOf (substr,[start]) : searches for and (if found) returns the indexOf the character or string searched in the string. If not found. Start is an optional argument that specifies the start of the search in the string. The default value is 0
Match (regEXP) : Searches for matches in a string based on a regular expression. If no match is found, a message number is returned as NULL
Replace: Used to replace some characters in a string with other characters, or to replace a string that matches a regular expression
28.Vue scaffolding download
NPM install -g vue -CLI install scaffolding
Vue init webpack VUe-demo initializes scaffolding
29. NPM common commands
NPM install Installs the module
NPM uninstall Uninstalls modules
NPM init bootstrapping creates a package.json file in your project
NPM root check its installation path output node_modules path
NPM ls View the installed modules
NPM start Starts the module
NPM stop Stops the module
NPM update Updates the module
NPM outdated checks whether the module is outdated
NPM restart Restarts the module
NPM help Displays the detailed help information about a command
NPM config Manages the NPM configuration path
NPM cache Indicates the cache of the management module
30. Common configurations and functions of Vue
El: outermost element selector
Props: Declares to accept those properties
Data: indicates status data
Computed: Calculates attributes
Methods: Event callback functions
Watch: Monitors property changes
Directives: Registers local directives
Filters: Registers local filters
Components: Configures components
31. Common instructions and functions of Vue
V-text: sets the label body text
V-html: Sets the body tag
V-if/V-else/V-show: Show/hide
V-for: traverses the display list
14. v-bind: a forced binding expression –
V-on: binding event listener, @
V-model: bidirectional data binding
31. The difference between == and ==
The former will automatically convert the type, the latter will not
32. Comparison of calculated attributes in Vue and Watch
A data property changes when the properties on which it depends change, and this is best done with computed properties
Watch monitors the variable you define. When the value of the variable you define changes, it calls the corresponding method, which is suitable for asynchronous operation when the data changes
33. How do I determine the value of this
Object: obj obj.test()
This is window test()
Var x = new fn() var x = new fn()
④ Call and apply calls, test. Call apply(obj) this is mandatory by the coder
34. Performance optimization scheme
Reduce manipulation of the DOM and avoid redrawing and rearranging
The number of requests is reduced to save network resources
Encapsulating function functions to achieve reuse
Careful closure
Function throttling, function shaking
Images load lazily and routes load lazily
35. Implementation principle of new
Create a new object, and the this variable refers to the object and inherits the prototype of the function
②. Properties and methods are added to the object referenced by this
36. The difference between EGT and POST
37. Let,var and const
var
-
Variables declared with var are global variables.
function textVar(){
var a=30; if(true){ var a=50; console.log(a); / / 50}; console.log(a); // find the nearest a};Copy the code
let
-
Let has the concept of scope, which is only valid within the block of code in which the let command resides.
function textLet(){
let a=30; if(true){ let a=50; // Scoped concept console.log(a); / / 50}; console.log(a); / / 30}; textLet();Copy the code
-
Let is ideal for use in a for loop, and an error will be reported if it is read externally.
for (let i = 0; i < 10; i++) { // … }
console.log(i); // ReferenceError: i is not defined Copy the code
Differences between let and VAR
-
Let does not have variable promotion, var will have variable promotion, that is to say, it is used when the variable is not declared, but its value is undefined. Let is not allowed to be used without declaration.
console.log(foo); //undefined var foo = 2;
console.log(bar); //ReferenceError let bar = 2; Copy the code
-
Let is not allowed to declare the same variable twice, in the same scope. Var can, but its value will be overwritten.
function letAndVar() { let a = 10; var a = 1; } / / an error
function letAndVar() { let a = 10; let a = 1; Function letAndVar() {var a = 10; var a = 1; } // Normal, but a will be 1Copy the code
const
-
Once declared, it cannot be modified. It is a constant.
const x=10;
x=100; console.log(x); //Uncaught TypeError: Assignment to constant variable.Copy the code
38. Responsive vs. non-responsive attributes for Vue instances
①. Reactive attributes
View updates are triggered when reactive properties are modified after the Vue instance initializes properties previously defined in data
②. Non-responsive attributes
Attributes added after Vue instance initialization. Adding or modifying non-responsive attributes does not trigger view updates
39. CSS styles display ellipsis
.ellipsis{
overflow:hidden;
text-overflow:ellipsis;
white-space:nowrap;
}
Copy the code
40.CSS methods to hide elements
(1). The display: none; Off-scale, does not occupy space, does not affect the layout, cannot respond to events
(2). Opacity: 0; Set element transparency, not off scale, occupy space can be corresponding to the event
(3). The visibility: hidden; Do not off-scale, do not want to respond to any user interaction
(4). Position: absolute; De-scaling, positioning elements away from the page
(5). The clip – path: polygon (0 px, 0 px, 0 px, 0 px, 0 px, 0 px, 0 px, 0 px); By cutting the box, not off the mark
41. What happens when a page is loaded and displayed from the input URl?
(1) The browser sends the requested URL to the DNS for domain name resolution, finds the real IP address, and sends a request to the server
②. The server returns data after the background processing is completed, and the browser receives files (HTML, CSS, JS, images, etc.)
③. The browser parses the loaded resources (HTML, CSS, JS, etc.) and establishes the corresponding internal data structure (such as HTML DOM).
④ load the parsed resource file and render the page
42. Why should CSS styles be initialized
Because of browser compatibility issues, different browsers have different default values for some tags. If CSS is not initialized, the page will appear differently in the browser to date
43. How to solve the gap problem on the page
display:inline-block
Remove the blank space
Using margin negative values
Use the font – size: 0
letter-spacing:word-spacing
44. How do I center a floating element vertically
A floating element can be vertically centered by positioning, which can be divided into known height and unknown height. The known height is pulled by negative margin. Unknown pull with Transion
45. The function of key in V-for
Key is primarily used to improve rendering performance
The key attribute prevents data clutter (which would occur if the element contained temporary data was not used).
46. The value of the position property
Absolute absolute positioning
Fixde fixes positioning
Relative positioning
The static default values
Inherit specifies that the value of the Position property should be inherited from the parent element
47. Method of clearing float
① use the Clear style
②. Using pseudo-elements
clearfix:after{
contant:'';
height:0;
display:block;
clear:both;
}
Copy the code
③ Overflow clearing float
48. Three major programming features of jQuery
Chain programming
Implicit iteration: You can operate on a DOM, an array, or a class array without iterating
Read-write two-in-one
49. Common jQuery methods
$.each(): Iterates over the data in a group or object
$.trim(): Removes whitespace from both sides of the string
$.type(obj): Gets the type of the data
$. IsArray (obj): Checks whether it is an array
$.isfunction (obj): checks whether it is a function
50. Differences between Vue and jQuery
Vue has less DOM manipulation than jQuery
Why reduce DOM manipulation?
A: When DOM manipulation affects the layout, the browser’s rendering engine recalculates and renders. More DOM manipulation leads to more computation, which naturally affects page performance, so less DOM manipulation is best
How does Vue reduce DOM manipulation?
A: Vue uses virtual DOM technology to reduce DOM manipulation. What is a virtual DOM? Use JS object to simulate DOM, in the process of operation will not operate DOM directly, wait for the completion of the virtual DOM operation, only compare the start and end state of the virtual DOM transformation, finally according to the end state of the virtual DOM to operate DOM, as for how to compare the virtual DOM is to use diff algorithm
Diff algorithm processing mode
Special scenarios are preferred
①. Nodes of the same type at the head and nodes of the same type at the tail
Such nodes do not change their position before and after the update, so they do not need to move their corresponding DOM
②. Same type of node for head/tail
The location of such nodes is obvious, so you don’t need to bother to find them and just move the DOM
In situ reuse
“In situ reuse” means the Vue can reuse as much as possible the DOM, as far as possible without DOM mobile, Vue in judging if a pointer pointing to the same node before and after the update, actually does not require them to refer to the same real DOM node, in fact it only to determine whether, pointing to the same department but hey, if it is not the same node, then the Vue will directly reuse the DOM, By docking text content, for example, this has the advantage of not having to move the DOM.
②.Vue supports bidirectional data binding
Data has one-way data binding and two-way data binding
What is one-way data binding?
Data affects pages, and pages do not affect data
What is two-way data binding?
Bidirectional means that the two aspects influence each other, front-end, that is, the data affects the page, the page affects the data. Such as: In the MVVM framework, the View and the Model cannot communicate directly. Between them lies the ViewModel, which acts as the observer. When the user manipulates the View, the ViewModel senses the change and notifies the Model of the corresponding change. Conversely, when the Model(data) changes, the ViewModel also senses the change, and the View updates in response.
In fact, v-Model is just syntax sugar, two-way binding is really the same as one-way binding +UI event listening, but Vue encapsulates the process in a black box
What are the benefits of two-way data binding?
Convenient, the data automatically updates, and the downside is you can’t tell where the data has changed, right
③.Vue supports componentization
Components of the web is actually part of the pages, like every component in a computer (such as hard disk, keyboard, mouse), it is an independent or page logic and function, and can according to the provisions of the rules of interface for mutual confluence, into a full application, page is one of such parts, such as navigation, list, Pop-ups, drop-down menus, etc. A page is just a container of these components, which can be freely combined to form a fully functional interface. When a component is not needed or a component needs to be replaced, it can be replaced or deleted at any time without affecting the operation of the entire application.
The nature of componentization
High cohesion: component functions must be complete, such as I want to achieve the drop-down menu function, then in the component of the drop-down menu, all the functions required by the drop-down menu are fully realized
Low coupling: In layman’s terms, code independence does not conflict with other code in the project. In practical engineering, we often involve team collaboration, and the traditional way of writing code according to the line of business can easily conflict with each other, so the use of componentization can greatly avoid the existence of such conflict
Each component has a clear subset of responsibilities, complete functionality, low coupling, and easy unit testing and reuse
A little bit of componentization
Improve development efficiency
Easy to reuse
Simplify debugging steps
Improve the maintainability of the entire project
Facilitate collaborative development
51.this.
The difference between the router
This.$router is a global routing object that contains a number of attributes and objects (such as the history object) that any page can call push(), replace(), go(), and so on
This.$route represents the current route object. Each route has a route object, which is a local object that can obtain the corresponding attributes such as name, path, params, query, etc
52. Benefits of route hops over A-tags
A real separation of the front and back ends, with the back end focused on data and the front end focused on interaction and visualization
53. What is the function of
A declaration that tells the browser to interpret the HTML document using the HTML version specification
54. Make a native Ajax request by hand
XHR let XHR = new XML HTTP Request(); Bind the listener to the object instantiated in the previous step, Call onReadyStatechange xhr.onReadyStatechange =function() {if(xhr.readyState === 4 &&xhr.states === 200){ The console. The log (XHR. Response)}} specify sends a request, address, parameter XHR. Open (' get 'and' http://localhost:3000/test? Name =zhansan') xhr.open()Copy the code
55. Array deduplication
Var array = [1,1,2,2,3,3,4,5,6,5]function unique(array) {var res = [] for(var I =0; i<array.length; i++){ for(var j=0; j<res.length; j++){ if(array[i]===res[j]){ break; } } if(j===res.length){ res.push(array[i]) } }console.log(res)return res; } unique (array) / / in this method, we use a nested loop and the outer circular array, the inside loop res, if array [I] value with res [j] values are equal, just jump out of the loop, if all is not equal to, that element is unique, then the value of j will be equal to the length of the res, Function unique1() {var res = []for(var I = 0; i<array.length; i++){ var current = array[i] if(res.indexOf(current) ===-1){ res.push(current) } } console.log(res) return Function unique2() {var res = []var sortedArray = array.concat().sort()var seenfor(var I =0; i<sortedArray.length; i++){ if(! i || seen ! == sortedArray[i]){ res.push(sortedArray[i]) } seen = sortedArray[i]} console.log(res) return res}unique2(array)// If the array is sorted by sort, the same values will be sorted together. If the array is sorted by sort, the same values will be sorted together. Filterfunction unique3() {var res = array.filter(function(item,index,array){return Array.indexof (item)===index})console.log(res)return res}unique3(array) //ES6// ES6 provides a new data structure set, which is similar to an array, but the values of the members are unique, Function unique4(array) {console.log(new Set(array))}unique4(array)Copy the code
56. Bubble sort
function test(arr) {
for(var i=0; i<arr.length-1; i++){
for(var j=0; j<arr.length-1-i; j++){
if(arr[j]<arr[j+1]){
var temp = arr[j]
arr[j] = arr[j+1]
arr[j+1] = temp
}
}
}
console.log(arr)
}
Copy the code
57. Depth copy of array
Shallow copy: Just equal the two arrays
Deep copy:
Use array traversal assignment
How it works: The original method is to fetch each value into another array
②. Use the array map method
Use the map method to iterate over the array and return a new array with the same values
③ Use concat method
The concatenated array, if the concatenated array is empty, returns its own value
④ Use ES6 syntax to achieve deep copy
The ES6 three-point operator implements deep copies of arrays, by far the simplest
⑤. For-in even the prototype chain is also copied
This method copies not only the values, but also the attributes
⑥. Copy multidimensional arrays
function deepClone(target) {
let result = null
if(target instanceOf Array){
result = []
}else if (target instanceOf Object){
result = {}
}else{
return target
}
for(let key in target){
let item = target[key]
if(item instanceOf Array || item instanceOf Object){
result[key] = deepClone(item)
}else{
result[key] = item
}
}
return result
}
Copy the code
58.Vue parent component lifecycle execution order
Loading the rendering process
-> Parent beforeCreate -> parent created -> parent beforeMount****-> child beforeCreate -> child created -> child beforeMount -> child Mounted -> parent Mounted
Child component update process
-> Parent beforeUpdate**-> child beforeUpdate -> Child updated****-> Parent updated**
Parent component update process
Parent beforeUpdate -> Parent updated
Destruction of the process
-> Parent beforeDestroy**-> Child beforeDestroy**-> Child destroyed**-> Parent destroyed**
59. Expansion box model (elastic box model)
(1). The flex container
display:flex; desplay:-webkit-flex; Chrome kernelCopy the code
②. The layout direction of the spindle
flex-direction:row; Horizontal, spindle default flex-direction:column; The main shaft and the side shaft are switchedCopy the code
③. The alignment direction of the spindle
flex-direction:row-reverse; Flex direction:column-reverse; flex direction:column-reverse; The spindle and the side axis are switched, and the spindle start and end are switchedCopy the code
④. Management of rich space (spindle, alignment of content)
justify-content:flex-start; The rich space on the right side is context-content :flex-end; The excess space is on the left justify-content:center; Rich space on both sides -content:space-around; Context-content :space between; Rich space in... Between the justify - content: space - evenly; The rich space is evenly distributedCopy the code
⑤. Management of affluent space (side axis)
align-items:flex-start; Align -items:flex-end; Align -items:center; Align -items:baseline; Align -items:stretch; Stretch, defaultCopy the code
⑥. Elastic space (expansion project)
flex-grow:1; Allocate spare space to projects (child elements)
The new version has attributes
①. Project implementation line wrap (Flex container)
flex-wrap:nowrap; Flex-wrap :wrap; flex-wrap:wrap; Flex --wrap:wrap-reverse; When a child element is wrapped, start and end are switched on the side axisCopy the code
②. Control the spare space of the overall side axis (Flex container) takes effect after line breaking
align-content:flex-start; Align -content:flex-end; The project is packaged as a whole and placed at the end of the overall side axis align-content:center; The project is packaged as a whole and placed in the center of the overall side axis. Note: If there is a conflict between align-items and align-content, check whether the element is wrapped. If there is a line wrap, align-content if there is a line wrap, align-content if there is a line wrap in a flex container, align-content if there is a line wrap in a flex container, align-content if there is a line wrap in a flex containerCopy the code
③. Order of items (Flex items) child elements
order:1; Order order, move to the back row, look at the number, order the large number in the front order, separate the sorting elements first, let the rest of the elements in normal order first, after the shoot, order the elements behind the order order along the main axisCopy the code
④ Spare space of the side axis of the project itself (Flex project)
align-self:flex-start;
align-self:flex-end;
align-self:center;
Copy the code
60. ES6 new features
61. Vue3 new features
62. What are the conditions that trigger the lifecycle of a Vue
①. When the browser refreshes
②. When a route is redirected
63. Array flattening
① use recursion
function flatten(arr) {
var result = [];
for (var i = 0, len = arr.length; i < len; i++) {
if (Array.isArray(arr[i])) {
result = result.concat(flatten(arr[i]))
} else {
result.push(arr[i])
}
}
return result;
}
Copy the code
(2). [1, 2, [3]]]. Flat (2)
64. Fibonacci series
1,1,2,3,5,8,13… The Fibonacci sequence works by saying that the sum of the first two digits equals the third digit
Solution: Loops and recursion
function fibonacci(n) {
if (n == 1 || n == 2) {
return 1
};
return fibonacci(n - 2) + fibonacci(n - 1);
}
fibonacci(30)
function fibonacci(n) {
var n1 = 1, n2 = 1, sum;
for (let i = 2; i < n; i++) {
sum = n1 + n2
n1 = n2
n2 = sum
}
return sum
}
fibonacci(30
Copy the code
65. Macro versus micro tasks
Macro tasks: whole generation script, setTimeout, setInterval
Microtasks: Promise, process.nexttick
The sequence of the event cycle determines the execution sequence of the JS code. After entering the overall code (macro task), the first cycle begins. Then perform all the microtasks. Then start from the macro task again, find one of the task queues to complete, and then execute all the microtasks.
66. Set the font size to less than 12px
Css3 attributes: transform:scale(0.5)
67. The difference between PX, REM and EM
① px is a unit of pixels, relative to the resolution of the display
Rem relative to element unit, relative to browser root element size, HTML tag
Em is the unit of the element relative to the size of the parent element
68. One-pixel border
Cause: it is mainly related to one thing, DPR(devicePixelRatio) devicePixelRatio, which is the ratio of device pixels to CSS pixels when the default zoom is 100%.
Window. devicePixelRatio= Physical pixel /CSS pixelCopy the code
The current mainstream screen DPR=2 (iPhone 8), or 3 (iPhone 8 Plus). For a 2x screen, the physical pixel of the device needs to be 1 pixel and the DPR=2, so the CSS pixel can only be 0.5. The 1px is 750, and the CSS style is 375, so we should write 0.5px. IOS 8+ is supported, Android is not.
Solution:
(1) :
Border: 0.5 px solid # FFF;Copy the code
You might ask why it’s not 0.3333px at 3 times? In my tests, I simulated the iPhone 8Plus on Chrome and found that it didn’t show up below 0.46px.
-
Advantages: Simple, no side effects
-
Cons: supports iOS 8+, not Android. Later Android Follow is good.
② : Use border pictures
border: 1px solid transparent; border-image: url('./.. /.. /image/96.jpg') 2 repeat;Copy the code
-
Advantages: No side effects
-
Disadvantages: border color changes, need to rework the image; Rounded corners tend to blur.
③ : Use box-shadow
box-shadow: 0-1px 1px 1px #e5e5e5, // Top line 1px 0 1px -1px #e5e5e5, // right line 0 1px 1px -1px #e5e5e5, // bottom line -1px 0 1px -1px #e5e5e5; / / the left lineCopy the code
-
Advantages: Easy to use, rounded corners can also be achieved
-
Disadvantages: analog implementation method, look carefully who can’t see that this is a shadow not a border.
④ use false elements
Article 1 the border
.setOnePx{ position: relative; &::after{ position: absolute; content: ''; background-color: #e5e5e5; display: block; width: 100%; height: 1px; / * no * / transform: scale (1, 0.5); top: 0; left: 0; }}Copy the code
-
As you can see, set the pseudo element to be absolutely positioned and aligned with the top left corner of the parent element, set width to 100%, height to 1px, and then shrink it by 0.5 times in the Y direction.
Article 4 the border
.setBorderAll{ position: relative; &:after{ content:" "; position:absolute; top: 0; left: 0; width: 200%; height: 200%; The transform: scale (0.5); transform-origin: left top; box-sizing: border-box; border: 1px solid #E5E5E5; border-radius: 4px; }} Copy the codeCopy the code
Also set the absolute positioning of the pseudo-element with the upper-left corner of the parent element. First enlarge the length and width of the pseudo-element by 2 times, then set a border with the top left corner as the center, and scale to 0.5 times the original
-
Conclusion:
-
Pros: Full compatibility, true 1px, and rounded corners.
-
Disadvantages: Temporary after pseudo-element, may affect cleanup float.
69. Differences between constructors and ordinary functions
1. The constructor is an ordinary function, and usually starts with a capital letter
2. The call method is different. Ordinary functions are called with the method name and parentheses, while constructors are usually called with the new keyword
3. The constructor is used to create new instance objects
4. Internally use this to build properties and methods
The constructor immediately creates a new object and returns that object as its return value
70. Why can’t v-if and V-show be used together
Reason: V-for has a higher priority than V-if, so every time v-for is used, v-IF is performed, causing unnecessary calculation and affecting performance, especially if it requires a small amount of rendering.
71. Vue3 new features
1.Vue3 designed a set of powerful composite API to replace the Optiom API in Vue2, which is more reusable
2. Better support for TS
3.Vue3 uses Proxy and Reflect instead of object.defineProperty () in Vue2 to achieve data responsiveness (data Proxy)
4. Rewrote the virtual DOM to make it faster
5. New component: Fragment /Teleport /Suspense
6. Designed a new scaffold tool, Vite
72. The arrow function this cannot be changed by call(),apply(), or bind()
73. Why is data in vue a function rather than an object
When multiple components are reused, each time the data function is called, a new object will be returned, and their memory addresses will be different so that they will not affect each other
74. How do attributes in an object be monitored in VUE
Add the deep:true attribute
75. Query parameter passing differs from Params parameter passing
Params can only be passed by name. Query can be passed by name or path
76. This $nextTick role
Action: Executes its specified callback after the next DOM update
When to do something based on the updated DOM after data changes in a callback specified by nextTick
77. Difference between hash and history
The most intuitive representation is one with a # and one without a #
Hash mode is more compatible and history is less compatible
History requires backend coordination
The hash pattern # is called the hash value
The hash value is not included in the HTTP request, that is, the hash value is not brought to the server
Solution: Backend coordination is required
You can use connect-history-api-fallback in Node.js
78. Common methods in arrays
Map () : Often used to iterate over data, returning a new array consisting of the return value of each element in the original array after calling a specified method
From () : Converts a pseudo-array to a real array
Find () : Returns the first qualifying element in the array
Includes () : checks whether an array contains an element, returning true if it does, false otherwise
79.for… In and for… The difference of
for… In and for… Of can be used to iterate over groups of objects, but for… “Of” cannot be used to iterate over objects because “for”… Of cannot be used to iterate over objects because objects have no Iterbale interface
for… The key for… The of traversal is the value