preface
Due to the factors of resistance, in the second half of the golden nine silver ten began to look for jobs. Interviews can really drive learning and categorization. In this article to record the interview process encountered questions, only for sharing, do not like spray.
js
Js event loop
Describe the JS event loop?
Short answer:
First, since JS is single-threaded, all tasks need to be queued. In addition, tasks are divided into Sync and Async to avoid blocking caused by slow I/OS.
Second,
1. Synchronization tasks are executed on the main thread, forming an execution stack (last in, first out).
2. In addition to the main thread, there is a “task queue” (first-in, first-out). When an asynchronous task has a run result, the callback function is placed in the task queue.
3. Once the call stack is cleared, the callback function of the “task queue” will be read into the stack to wait for the execution of the main thread
That’s the three steps of the cycle.
Then, it is important to note that task queues are divided into macro task queues and micro task queues.
When the call stack is empty, all the microtasks in the microtask queue are read first (e.g. Promise.then), and then the macro tasks in the macro task queue are read (e.g. SetTimeout).
After each macro task is executed, check whether the microtask queue is empty. If it is empty, execute the next macro task. Otherwise, all the microtasks in the microtask queue will be read and executed.
Macro tasks: Script, setTimeout, setImmediate, Executor in promise
Microtasks: Promise.then, process.nexttick
Further: Personal understanding of QAQ
Go to dining room dozen rice, only row a team, the aunt of the window ask you want what ah?
1. If you ask for a barbecued and roasted duck rice (which is already cooked and put in the window), your aunt makes the rice and gives it to you, and then the next one;
2. If you want bacon fried rice (need to cook on the spot), aunt will tell this need, and then ask you to wait beside, do not affect the next student cooking rice;
3 uncle fried rice, to the aunt, aunt at this time to another student to play double, she will first put the hands of the double play to the students, will put the bacon fried rice to you;
4. But apart from making fried rice, he also needs to make hand-made cakes. If you’re unlucky enough to lose a bet, you need to bring one or more crackers for your roommate. Kind-hearted Uncle will fry your rice after the hand grab cake also to do, and then to do the next fried rice.
In this scene, the rice team is the “main thread” stack, playing double rice is the “synchronous task”, making fried rice, making hand-scratch cake is the “asynchronous task”, the fried rice is the “macro task”, the hand-scratch cake is the “micro task”;
Reference links:
Concurrency model and event loop
Tasks, microtasks, queues and schedules
Learn the Event Loop once
Recommended reading:
Eventloop is not scary. It’s scary to meet a Promise
Js native handwriting
Ask for handwriting! (Some people (me) who started writing pages in jquery and moved on to Vue tend to ignore or forget how to write native.)
Example:
- document.querySelector(“h2, h3”).style.backgroundColor = “red”;
- document.getElementById(“demo”);
- document.getElementsByTagName(“P”); .
Reference links:
- HTML DOM Document object
Js prototype chain
Short answer:
To implement inheritance, one of the most basic concepts in common object-oriented languages, javaScript implements it based on prototype chains.
When accessing an object’s properties, look in the base properties first, if not, up the chain of implicit archetypes _proto_
(because obj. _proto_ = = = obj. Constructor. The prototype, the object of the implicit stereotype _proto_ is equal to the structure of the object function display prototype prototype)Copy the code
Further:
The constructor operator is used to check whether constructor. Prototype exists on the constructor chain
2. Basic types (Undefined, Null, Boolean, Number and String), reference types (Object, Array and Function)
3. All (reference types) are objects, which are collections of attributes. An Object is essentially made up of an unordered set of name-value pairs
4. Objects are created by functions
5. Every function has a prototype. Each object has a __proto__, which can be an implicit prototype pointing to the prototype of the function that created it.
Function.prototype.__proto__ === Object.prototype obj.__proto__=== Object.prototype //Object.prototype This is a special case -- its __proto__ is null, remember!Copy the code
Almost all objects in JavaScript are instances of Object at the top of the prototype chain.
Reference links:
In-depth understanding of javascript archetypes and closures (6) — inheritance
Closure principle
Short answer:
A closure is a combination of a function and the lexical environment in which it is declared. – MDN
In such a lexical environment, the variable collection mechanism prevents the variable collection mechanism from accessing variables in the function’s internal scope.
function init() {
var name = "Mozilla"; // Name is a local variable created by initfunction displayName() {// displayName() is an inner function, a closure alert(name); // use a variable declared in the parent function} displayName(); } init();Copy the code
further
- Recycling mechanism
function a(){
var i=0;
function b(){
alert(++i);
}
return b;
}
var c=a();
c();
Copy the code
In Javascript, if an object is no longer referenced, then the object is collected by GC. If two objects refer to each other and are no longer referenced by a third party, the two objects referred to each other are also reclaimed. Because function A is referred to by B, which in turn is referred to by C outside of A, this is why function A is not recycled after execution. (Source: Wikipedia)
- Closure and
Best:
① You can read variables inside the function
② Keep the values of these variables in memory and will not be automatically cleared after f1 calls.
Bad:
(1) The variables in the function are stored in memory, which consumes a lot of memory, so do not abuse closures, otherwise it will cause performance problems on the page.
The actual encounter
let r=[]
for (leti=0; i<5; i++) {let index=i+1
let res_all=vm.$apidAllService (100, 1, index). Then ((val) = > {/ / allService,1,1 (100) the size, current, serviceTypelet res=val.data.data.records
r[i] = res.map(item => {
return {
name: item.serviceName,
key: item.serviceId,
icon: vm.$store.state.myBaseUrl+vm.$store.state.devurl + item.imgurl, cat: index}}) console.log(r)})}// Problem with loop request asynchroCopy the code
Reference links:
MDN – closure
Recommended reading:
- In-depth understanding of javascript prototypes and closures
- Basic data types
- Closure details 1
- JS closure example demonstration
Note: Closures, scopes, prototype chains, and JS data types will all come together at some point during the learning process. This is the “most basic” of JS!
AddEventListener loop binding
Interview question: addEventListener loop binding, how to improve the following code to implement correctly? How many ways are there?
<a>1</a><a>2</a><a>3</a>
var elems = document.getElementsByTagName('a');
for (var i = 0; i < elems.length; i++) {
elems[i].addEventListener('click'.function (e) {
e.preventDefault();
alert('I am link #' + i);
}, 'false'); }; // This code is wrong, because the variable I is never locked // Instead, after the loop executes, we get the value of I when we click on it // because that's when I really gets the value // so whatever connection we click on, we end up with I am link#3 (if there are three A elements)
Copy the code
Solution 1: use a closure to solve var elems = document. The getElementsByTagName ('a');
for (var i = 0; i < elems.length; i++) {
elems[i].addEventListener('click', (function (num) {
return function(e){
e.preventDefault();
alert('I am link #' + num);
}
})(i), 'false'); }; // Since I is an external variable, we can pass the value of I into the anonymous function when loop binding. So you need to wrap an anonymous function around an anonymous function (event function) and execute it immediately. Solution 2: Replace var with varlet
var elems = document.getElementsByTagName('a');
for (let i = 0; i < elems.length; i++) {
elems[i].addEventListener('click'.function (e) {
e.preventDefault();
alert('I am link #' + i);
}, 'false'); }; The variable promotion mechanism of the //var command is implemented only once. / /,letThere is no variable promotion, so each time the loop is executed, a new variable is declared (but initialized with a different value). //forEach loop is a different block-level scope, //letDeclared variables are block-scoped, so there is no problem with duplicate declarations.letVitally variableforCycle, each anonymous functions actually reference is a new variable to solve 3: useless to closure solve var elems = document. The getElementsByTagName ('a');
for (var i = 0; i < elems.length; i++) {
elems[i].num = i;
elems[i].addEventListener('click'.function (e) {
e.preventDefault();
alert('I am link #' + this.num);
}, 'false');
};
Copy the code
References:
- Why is this js loop addEventListener wrong?
Variable ascension
Interview questions:
(function(){ console.log(a)//undefined var a=1; }) () (function(){console.log(a)// Error: Cannot access'a' before initialization
leta=1; }) () (function(){
{letA =1} console.log(a) : a is not defined})()Copy the code
Short answer:
Js has variable promotion and function promotion, which refers to the declaration of variables using var or function name () {}, will be promoted to the top in the js pre-parsing phase; (Es6 lets and const are not promoted.) Second, function promotion takes precedence over variable promotion
webpack
Webpack packaging principles
Short answer:
Website:
In essence, Webpack is a static Module bundler for modern JavaScript applications.
When Webpack works with an application, it recursively builds a Dependency graph containing every module the application needs, and then packages all of those modules into one or more bundles
Memory points: static module packers, dependency diagrams, bundles
From a front-end engineering perspective (” front-end engineering “is a plus) :
Tools like Webpack are front-end engineering tools. Front-end engineering is a series of processes that bring front-end development into a more systematic and normative system. This process includes source code precompilation, module processing, code compression, and other construction work.
Webpack’s “everything module” and “load on demand” features make it better suited for engineering.
Memory points: precompilation, code compression, module processing, on-demand loading
Further:
Webpack mainly deals with the following issues in packaging: 1. Analyze the dependency tree of the entire application from the entry file 2. Wrap each dependent module and put it in an array to wait for calling. 3. Implement the method of loading modules and provide it to the environment of executing modules so that modules can call each other. Put the logic to execute the entry file in an immediate function expressionCopy the code
- e.g. webpack.config.js
Module. exports = {// exports = {// exports'development', // production // Specifies the entry file to be packaged.'./src/js/index.js'Output: {path: path.resolve(__dirname,'dist'),
filename: 'main.min.js'}, // Configure the resource loader module: {rules: [// configure the js loader (ES6 to ES3/5 code) {test: /\.jsx? $/, loader:'babel-loader'// Exclude: path.join(__dirname,'./node_modules'), // Package the included file include: path.join(__dirname,'./src'}, // configure the CSS loader {// match the.css ending filetest: /\.css$/, // Configure the CSS file loader, processing order: right to left use: ['style-loader'.'css-loader'}, // configure less loader {test: /\.less$/,
use: ['style-loader'.'css-loader'.'less-loader'}}, // plugins: [new CleanWebpackPlugin(), // Generate HTML new HtmlWebpackPlugin({title:'Test title',
template: 'index.html'})], // devServer: {contentBase: path.join(__dirname,'dist'),
port: 5000
}
}
Copy the code
Reference links:
Webpack – Webpackjs.com
When we talk about front-end engineering, what are we talking about
Webpack packaging principles
Recommended reading:
May there be no Webpack in the future
Webpack configures multi-page applications
Short answer:
There are two ways to build a multi-page application with WebPack,
1. Configure multiple pages and one page. The htML-webpack-plugin in Entry and plugins should be modified.
2. Multiple pages and multiple configurations. The advantage of multi-page single configuration is that different pages can share the same code, making it easy to implement long caching. The main disadvantage is that as the project gets bigger, the packaging speed will decrease significantly.
More entry, modify plugin
var webpack = require('webpack');
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const CleanWebpackPlugin = require('clean-webpack-plugin'); Module. exports = {// exports: {about:'./src/pages/about/about.js',
contact: './src/pages/contact/contact.js'}, // configuration exit output: {path: __dirname +"/dist/",
filename: 'js/[name]-[hash:5].js',
publicPath: '/'}, module: {loaders: [// parse.js {test: '/\.js$/',
loader: 'babel',
exclude: path.resolve(__dirname, 'node_modules'),
include: path.resolve(__dirname, 'src'),
query: {
presets: ['env'}}, // CSS processing {test: /\.css$/,
loader: 'style-loader! css-loader'}, // less {test: /\.less$/,
loader: 'style-loader! css-loader! less-loader'}, // image processing {test: /\.(png|jpg|gif|svg)$/,
loader: 'file-loader',
query: {
name: 'assets/[name]-[hash:5].[ext]'}, {},test: /\.(htm|html)$/i,
use:[ 'html-withimg-loader']
}
]
},
plugins: [
new ExtractTextPlugin(__dirname + '/assert/css/common.less'),
// minify:{
// removeComments: true// collapseWhitespace:true} new HtmlWebpackPlugin({filename: __dirname +'/dist/about.html',
inject: 'head',
template: 'html-withimg-loader! '+__dirname + "/src/pages/about/about.html",
chunks: ['about'],
inlineSource: '.(js|css)$'
}),
new HtmlWebpackPlugin({
inject: 'head',
filename: __dirname + '/dist/contact.html',
template: __dirname + "/src/pages/contact/contact.html",
chunks: ['contact'],
inlineSource: '.(js|css)$'Dist New CleanWebpackPlugin([dist New CleanWebpackPlugin(])'dist/*'.'dist/*',],  // Match the deleted file {root: __dirname,                     // root directory verbose:true,                     // Enable output messages on the console dry:false                    Dist devServer: {contentBase:"./dist/".historyApiFallback: true,
inline: true,
hot: true,
host: '192.168.1.107'// My LAN IP}}Copy the code
Further: Differences between single-page apps and multi-page apps
SinglePage Web Application (SPA) | MultiPage Application (MPA) | |
---|---|---|
composition | A shell page and multiple page fragments | Multiple complete pages constitute |
Resource sharing (CSS, JS) | Shared, only need to load in the shell part | No, each page needs to be loaded |
Refresh the way | Partial page refresh or change | A full page refresh |
Url patterns | a.com/#/pageone a.com/#/pagetwo |
a.com/pageone.html a.com/pagetwo.html |
The user experience | Switching between page fragments is fast and user experience is good | Page switching loading is slow, the fluency is not enough, and the user experience is poor |
Animated transitions | Easy to implement | Unable to realize |
The data transfer | easy | Depend on URL parameter transfer, cookie, localStorage, etc |
Search Engine Optimization (SEO) | It requires a separate scheme and is difficult to implement, which is not conducive to SEO retrieval using server-side rendering (SSR) optimization | Simple implementation method |
The trial scope | High requirements of experience, the pursuit of smooth interface applications | Ideal for applications that seek high search engine support |
Development costs | High, often with the help of professional framework | Lower, but more page repetition code |
Maintenance costs | Relatively easy to | Relatively complicated |
Reference links:
Comparison and analysis of single-page and multi-page applications
Webpack4 builds multi-page applications
vue
Principle of bidirectional binding
Short answer:
Vue internally converts every read and write of data in a data Object into a getter/setter by intercepting the Object. DefineProperty method attribute, notifying the view of updates when data changes.
Object.defineproperty:
The object.defineProperty () method directly defines a new property on an Object, or modifies an existing property of an Object, and returns the Object.
Object.defineproperty (obj, prop, Descriptor) OBj: Object on which attributes are to be defined. Prop: The name of the property to define or modify. Descriptor: Attribute descriptor to be defined or modified.Copy the code
Further:
Object.defineproperty ()
// This code is too important to remember!let hr={
skill:' ',
experience:' '
}
Object.defineProperty(hr, 'skill', {
get(){
console.log('Necessary Skills:')
return 'Don't stand up'
},
set(newVal){
console.log(Experience requirements:// Read: console.log(hr. Skill) // Write: hr. Skill ='Five-year start'
Copy the code
Console printing necessary skills: Do not release pigeons experience Requirements:"Five-year start"
Copy the code
Publish and subscribe model
Now that you can detect data reads and writes, you need to notify the view of updates.
Here is a typical publish-and-subscribe pattern, in which the data is the publisher (Observer), the dependency object is the subscriber (Watcher), and they need a middleman, the subscriber (Dep), to deliver it.
Summary: To implement bidirectional data binding, we first need to hijack the data listener, so we need to set up a listener Observer to listen for all properties. If the property changes, Watcher needs to be told if it needs to be updated. Since there are many subscriber Watchers, we need to have a message subscriber Dep that collects these subscribers and manages them uniformly between the listener Observer and subscriber Watcher.
Side note: See from this life cycle diagram when data and views are updated bidirectionally
Reference links:
Object.defineProperty() -MDN
Understand the principle and implementation of Vue bidirectional binding
Vue life cycle
Recommended reading:
Publisher-subscriber pattern -Microsoft Azure
v-for key
Short answer:
-
When you write v-for, you always have to add a key attribute to the element
-
Key’s main purpose is to improve rendering performance!
-
The key attribute prevents data clutter (which would occur if the element contained temporary data was not used).
Special note:
When v-if is used with V-for, v-for has a higher priority than V-if, which means that V-IF will be repeated separately in each V-for loop. Therefore, v-if and V-for are not recommended!
$nextTick
$nextTick is a deferred callback after the next DOM update loop ends, and when you use nextTick after modifying the data, you can retrieve the updated data in the callback
What do you think of this example
DOM:
After triggering changeMsg:
In changeMsg(), change the MSG value to ‘Hello World’ and then change msg1, MSG2, msG3 by getting the DOM value. $nextTick: msg2 is’ Hello World ‘, msg3 is’ Hello vue ‘. However, the value obtained through DOM at this time has not changed, so we can know:
When vue changes a value in response, the DOM is not updated immediately. If you need to do something with the DOM immediately after the data changes, you can use $nextTick to get the updated DOM.
Reference links:
- Deep into the responsivity principle
Virtual DOM
Short answer:
The realization principle of virtual DOM mainly includes the following three parts:
JavaScript objects are used to simulate the real DOM tree and abstract the real DOM. Diff algorithm — Compare the difference between two virtual DOM trees; Pach algorithm – The difference between two virtual DOM objects is applied to a real DOM tree.
Recommended reading
In Depth: The Virtual DOM at the heart of Vue
The browser
Browser cache
Short answer:
The browser cache is used to optimize performance. By repeatedly invoking the local cache to reduce Http requests, the browser can reduce latency, bandwidth, and network load.
-
Process: browser sends request, access cache, no cache result, initiate HTTP request, return result and cache, store cache
-
The cache types are cookie, LocalStorage, and sessionStorage
Further:
- CDN cache
The client obtains data directly from the source site. If the number of visits to the server is heavy, the access speed and user experience are affected. In addition, the distance between the client and the source site cannot be short enough for data transmission.
CDN is to solve how to quickly and reliably transfer data from the source site to the client. Through the distribution of data by CDN, users can obtain data from a server close to the source site, rather than the source site, so as to achieve fast access and reduce the load pressure of the source site.
Reference links:
Have an in-depth understanding of the browser caching mechanism
Talk about CDN caching
What happens from entering the URL to loading the page
Short answer:
TCP connection 3. Sending an HTTP request 4. The server processes the request and returns HTTP packet 5. The browser parses the rendered page 6. The connection ends
Performance optimization
Short answer:
Optimization method, combined with Yahoo military regulations 35 standards, can be roughly divided into so 6 categories (not strict, there are arranged according to their own understanding) :
Classification of | content |
---|---|
network | 1. Reduce the size and number of requests; 2. Reduce DNS lookup and avoid redirection. 3. Cacheable asynchronous requests; 4. Preloading, delayed loading, on-demand loading; 5. Reduce Dom number, etc.; |
service | 1. Use CDN; 2.Gzip component compression; 3. The Etag configuration; 4. Refresh Buffer as soon as possible; |
The cache | 1. Reduce the Cookie; 2. The CDN cache; |
CSS/JavaScript | 1. Put Css on top and Js on bottom to avoid blocking; 2. Compress Css and Js; 3. Reduce Dom access operations; 4. Reduce redrawing and avoid backflow; |
The picture | 1. Compress pictures; 2. Use iconfont; 3. Sprite; |
other | 1. Control the size of components; 2. Use precompiled languages, package them into modules and load them on demand; |
Reference links:
Yahoo! Catch
The front security
Short answer:
XSS: Cross Site Scripting is the most common and basic method of attacking WEB sites. Attackers inject illegal HTML tags or javascript code to control the user’s browser while browsing the page.
CSRF: Cross-site Request Forgeries, also known as one-click attacks or session riding. Impersonate the user to initiate a request (without the user’s knowledge), complete some things against the user’s will (such as modifying user information, deleting the initial comments, etc.).
Defense against: same-origin detection and double cookie detection.
Css layout
layout
Short answer:
The name of the | content |
---|---|
Static Layout | Regardless of the browser size, the layout of the web page remains the same as when the code was originally written. |
Liquid Layout | Fence system (grid system) : represents :bootstrap |
Adaptive Layout | When the screen resolution changes, the position of the elements on the page changes without changing their size. |
Responsive Layout | Each screen resolution has a layout style that changes the position and size of elements. |
Flexible layout (REM/EM layout) | Rem/EM difference: REM is relative to the font size of an HTML element, while EM is relative to its parent element. |
Further: rem and PX conversion
Assume the design is 750px wide and look at the HTML {font-size:XXXpx} for a 750px wide page.
Assuming the page width is 750px, HTML {font-size:100px} means 100px=1rem. In this case, you want to set the width of a button. In the design, the button is 200px90px, so the converted button is 2rem.9REM
HTML {//750 screen size=10px; } @media screen and (min-width: 640px){HTML {font-size:? ; What are the values in the question mark? Solution: 750/640 = 10 / xCopy the code
Layout instance
Requirements: only CSS implementation, a div is divided into two parts, the upper part of the height is not fixed, the lower part automatically fill the rest of the height
Method 1: Use Flex layout
.wrapper{ display:flex; flex-direction: column; }. Body {flex:auto; // Automatically fill the remaining space}Copy the code
Method two: use absolute positioning, and then add a height placeholder box to the DOM
Throttling stabilization
Recommended reading:
- 7 minutes to understand the throttling, anti-shaking and application scenarios of JS
algorithm
Handwritten dichotomy
Ask for handwriting!
function binary_search(arr,target) {
let min=0
let max=arr.length-1
while(min<=max){
let mid=Math.ceil((min+max)/2)
if(arr[mid]==target){
return mid
}else if(arr[mid]>target){
max=mid-1
}else if(arr[mid]<target){
min=mid+1
}
}
return "null"} the console. The log (binary_search (,5,7,19,88 [1], 19)) / / 3Copy the code
Bubble sort
Var arr =,20,50,100,40,200 [10];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
duplicate removal
1. Not considering Set()
2. Poor performance without considering double-layer for loop
Use the attributes of the object not to duplicate:
function distinct(arr) {
let result = []
let obj = {}
for (let i of arr) {
if(! obj[i]) { result.push(i) obj[i] = 1 } }return result
}
Copy the code