Front-end interview learning
It begins on March 17, 2021.
Welcome to point out any mistakes!
Note: The content is concise, equivalent to notes, and not finished… The frontal 😜
JavaScript based
JS data type
Basic types: null, and undefined, number, Boolean, string, symbol, reference types: object
-
When other conversions, such as the parseInt conversion, are performed on a string, the NaN returned (NaN belongs to number) returns false when compared to the NaN obtained by another string conversion. Since ‘A’ is not A number and ‘B’ is not A number, it cannot be proved that the two are the same! So use the isNaN() method.
-
Stack to store variables and their values. The base type is its actual value, and the reference type holds the value of the object’s address in the heap. So when you compare primitive types, you compare actual values. A reference type (Object) is compared to the address value, and assignment is also assigned to the address value in the heap.
let a={},b=a,c={}; console.log(`${a===b}.${a==c}`); //true,false Copy the code
-
Boolean ->Boolean, Numbe ->Numbe int->Integer, Boolean ->Boolean. When a method is called on a primitive type or an attribute is retrieved, a wrapper class is implicitly created and destroyed when used.
var str = 1; str.pro = 2; console.log(str.pro + 10); // NaN Copy the code
-
Understand that object assignment is passing references. The object depth copy problem is solved.
-
Use typeof to see what type it belongs to. Array [] is also object. Functions return function. Typeof null returns object. The js engine defines object as null if the first three digits are 0. (It can be changed, but not necessary)
-
For Boolean conversions, all values except undefined, null, false, NaN, “, 0, -0 are converted to true, including all objects.
Prototype and prototype chain
==👈 famous JS prototype graph ==
= = = = concise
- Js implements inheritance-like mechanisms through prototypes and prototype chains. Just like inheritance in OOP, superclasses in Java, class methods, etc.
In Java, you can use Cat Cat =new Cat(); Cat.eat() calls methods belonging to a class or can be called directly using cat.eat(). Because of the dynamic language nature of JS, you can add methods and properties to ‘classes’. Make its’ instance objects’ available to call this method. Inheritance also lets the instance know who its parent is.
-
Const fun1=()=>{} Creates a function that has no prototype property
const fun4=(){ console.log('is func4') } fun4(); // is func4 console.log(fun4.prototype); // undefined Copy the code
-
Using function to declare a function is actually an internal call to new function (…) The __proto__ attribute is added to link to its constructor prototype.
-
Object is the parent of all objects, and all objects can be found by __proto__
-
Function is the father of all functions, all functions can be found by __proto__
-
Prototype and Object.prototype are two special objects that are created by the engine
-
Except for the above two special objects, all other objects are generated through the constructor new
-
The prototype of a function is an object
-
An object’s __proto__ refers to the prototype, and __proto__ connects the object to the prototype to form the prototype chain
-
The _proto_ attribute for all reference types points to the prototype of its constructor
-
From github.com/KieSun/Drea…
The keywordnew
- use
new FunctionName
To create an object, four things happen: regenerate an object, link to a prototype, bind this, and return a new object - It’s best to create objects literally
let a = { b: 1 }
Method to create, high readability, good performance.
The keywordinstanceof
-
__proto__ let obj={}; let obj={}; console.log(obj instanceof Object) // true
function instanceof(left, right) { // Get the prototype of the type let prototype = right.prototype // Get the prototype of the object left = left.__proto__ // Determine whether the type of the object is equal to the prototype of the type while (true) { if (left === null) return false if (prototype === left) return true left = left.__proto__ } } Copy the code
The keywordthis
Official Chinese document directions
Developer.mozilla.org/zh-CN/docs/…
- This is an attribute of the execution context that will be used during execution. It points to depending on where it is called, and looks nearby, when called by a DOM event, this points to the caller, okay
- You can use call,apply, and bind to change this to the object passed in as an argument
- The arrow function ()=>{} has no this, so this looks up one layer at a time. And this is bound to the context and will not be changed
- In strict mode, this occurs when a function is called directly (not as an object property/method)
undefined
. - Use the new keyword to new an object, bind it to this, and implicitly return this
Other unresolved issues:
- The event handler calls this to point
The keywordvar,let,const
- Let, like const, is block-level and cannot be used before declaration. Const cannot change a reference/value and is assigned an initial value when it must be defined
- In a variable promotion, a function with the same name overrides the previous one, and the function takes precedence over the variable promotion
CommonJs and ES6 Module
CommonJs provides exports and require
TODO
closure
-
There’s a saying: closures are lazy people’s objects, objects are natural closures. Closures allow stateless functions to have state and record the variables used by the function.
-
However, closure references to variables keep reference types referenced and cannot be GC, which can lead to memory leaks if used incorrectly
var a = 1; function foo() { var b = 2; return function innerFoo() { console.log(a,b); }}const foo1=foo(); foo1(); //1,2 because of the closure, the function innerFoo records its context. B is quoted, it's not released. Copy the code
-
TODO usage scenarios:
Depth copy
-
Shallow copies copy the attributes of the first layer, deep copies do not work. Deep copy can be serialized and deserialized using JSON (ignoring undefined, symbol, and function).
let a = { age: 18.addr: { city: 'xiamen'}}let b = Object.assign({}, a) // let b = {... A} Deconstruction is also convenient a.age = 20; a.addr.city='chongqing'; // Modify the properties of object A console.log(a.age, b.age) / / 20, 18 console.log(a.addr.city, b.addr.city) // chongqing chongqing Copy the code
modular
-
ES Modules are unique to ES6. Handy, static import, dynamic reference, import and export all point to the same memory address
-
CommonJs is a Node specific specification that cannot be used directly by browsers. It supports dynamic import and the exported file is not the same as the imported file.
-
[javascript modularization evolution and Principle analysis] juejin.cn/post/694016…
Promise
- Promise changes the asynchronous function’s original callback processing to chained processing
.then().then() ...
Then () async
andawait
Es7.await
To wait for aPromise
Object. Instead of.then()
In the writing.async
Used to define an asynchronous function that returns onePromse
Object.async
andawait
Is the syntactic sugar for Generator functions,await
withyield
Commands have the same effect. Await must be in the context of async function
Generator
-
Generator is a new syntax in ES6 that, like Promise, can be used for asynchronous programming
// Use * to indicate that this is a Generator function // The code can be paused internally by yield and the value of the internal state can be declared // Resume execution by calling next function* test() { let a = 1 + 2; yield 2; yield 3; } let b = test(); console.log(b.next()); // > { value: 2, done: false } console.log(b.next()); // > { value: 3, done: false } console.log(b.next()); // > { value: undefined, done: true } Copy the code
-
As you can see from the above code, the function with * has the next function, which returns an object. Each call to the next function continues execution of the suspended code.
-
When a Generator function encounters a yield command inside, it stops executing and gives execution authority to another function. Other functions complete, return the right to execute before continuing to execute.
Proxy
TODO
Map
The difference between map and Object
Source: juejin. Cn/post / 694094…
Map | Object | |
---|---|---|
The accident of key | Map contains no keys by default, only explicitly inserted keys. | Object has a prototype, and the key name on the prototype chain may conflict with the key name you set on the Object. |
The type of the key | Map keys can be of any value, including functions, objects, or any primitive type. | The key of Object must be either String or Symbol. |
The order of the keys | Keys in a Map are ordered. Therefore, when iterating, the Map returns key values in the order they were inserted. | The key of Object is unordered |
Size | The number of key-value pairs for a Map can be easily obtained using the size attribute | The number of key-value pairs of Object can only be calculated manually |
The iteration | Maps are iterable and can be iterated over directly. | Iterating over an Object requires that you somehow get its keys before you can iterate. |
performance | This is better when key pairs are frequently added or deleted. | Optimizations are not made in cases where key/value pairs are frequently added and removed. |
XMLHttpRequest
use
let xhr = new XMLHttpRequest();
xhr.open("post"."http://localhost:8080/api/test");
xhr.setRequestHeader("Content-type"."application/json");
xhr.send(JSON.stringify({a: 1.b: 2 }));
xhr.onreadystatechange=function(){
if(xhr.status==200 && xhr.readyState==4) {let result=xhr.responseText;// Get the resultalert(result); }}Copy the code
for in & for of
for… Of is new in ES6 and is used to iterate over groups of numbers, array-like objects, strings, sets, maps, and Generator objects. We get the value of the object.
// Common objects use for... Of traversal from: https://juejin.cn/post/6940945178899251230#heading-77
var obj = {
a:1.b:2.c:3
};
// Method 1:
obj[Symbol.iterator] = function(){
var keys = Object.keys(this);
var count = 0;
return {
next(){
if(count<keys.length){
return {value: obj[keys[count++]],done:false};
}else{
return {value:undefined.done:true}; }}}};for(var k of obj){
console.log(k);
}
/ / method 2
obj[Symbol.iterator] = function* (){
var keys = Object.keys(obj);
for(var k of keys){
yield [k,obj[k]]
}
};
for(var [k,v] of obj){
console.log(k,v);
}
Copy the code
for… In is basically for traversal. We get the key of the object.
let obj={a:1.b:2}
for (const key in obj) {
console.log(key);
}
Copy the code
Event loop
Microtasks: Promise. Then catch finally, MutationObserver
Macro tasks: Script, setTimeout(), setInterval(), requestAnimationFrame(), IO
The main thread script must be executed first. There are micro tasks, micro first, micro then look at the macro task queue.
Each time you do a macro task, you have to check if there are any other tasks in the microtask queue and execute all the microtasks first.
Flow of events
The event flow consists of three phases: the event capture phase, the target phase, and the event bubble phase.
< p id = "parent" > parent element < span id = "child" > child element < / span > < / p >
Parent captures first → child captures → child bubbles → parent bubbles
Async and defer in the script tag
Async: Start another thread to download the JS file. (This is when blocking occurs)
Defer: Start another thread to download the JS file and wait until the page has finished loading. (Not blocking at all)
In development, defer is often used for steps that require the entire DOM (depending on the order of execution) and Async for standalone scripts such as counters or advertisements
JavaScript interview questions
-
【Q003】 What are anti-shake and throttling, and what are their application scenarios
Anti – shake: mainly take the last time for multiple operations to avoid repeated operations. There are immediate execution and deferred execution.
Immediate execution: click to follow, send the request first, and then return the result before the click between invalid.
Deferred execution: multiple operations, only the last operation to execute the function. For example, click login and send SMS
Throttling: Controls the frequency of events, such as rolling events, calculated once per second.
-
What is Symbol
ES6 introduces a new base type, like a unique identifier ID, to create instances through Symbol()
Symbol can be used as the key of an Object and is used in serialization, object.keys () or for… Enumerations in will not be included
So you can also use Symbol to define a class’s private properties/methods. In general, very little.
-
Handwritten bind() and Promise
-
Handwritten JS inheritance
-
Reduct flatten arrays
function fn(arr){ return arr.reduce((prev,cur) = >{ return prev.concat(Array.isArray(cur)? fn(cur):cur) },[]) }Copy the code
CSS based
recommended
- A relatively complete summary: 15,000 words CSS basics (core knowledge, common requirements) : juejin.cn/post/694120…
- CSS chapter -100 words to help you consolidate CSS knowledge: juejin.cn/post/684490…
- 49 CSS facts you may not know: juejin.cn/post/684490…
Psition positioning
- Static: indicates the default location
- Relative: relative to its normal position
- Absolute: Out of the document flow with respect to the parent element that was most recently positioned as non-static
- Fixed: Generates fixed positioned elements relative to the browser window!
- Sticky: sets fixed and relative, but is controlled by the parent elements. The top attribute needs to be set. When the element is close to the top distance {{top}}, relative changes to fixed, but the parent element scrolls out
- Inherit: Inherits the position property of the parent element
Overflow spill
From: juejin. Cn/post / 684490…
Attribute values | describe |
---|---|
visible | Do not cut content or add scroll bars |
hidden | Do not display content that exceeds the size of the object |
scroll | The scroll bar is always displayed whether the content is exceeded or not |
auto | Beyond the automatic display of the scroll bar, not beyond the scroll bar |
Text overflow processing:
/*1. Force the text */ to be displayed on a line
white-space: nowrap;
/*2. Hide the excess part */
overflow: hidden;
/*3. Replace the excess */ with ellipses
text-overflow: ellipsis;
Copy the code
BFC (Block-level formatting Context)
A BFC is a separate container on the page (cutting off the interaction between elements inside and outside the space), and the child elements inside the container do not affect the outside elements. And vice versa.
-
Which conditions can be triggered
-
Body root element
-
Float element: float a value other than None
-
Absolute position elements: Position (Absolute, fixed)
-
Display inline-block, table-cells, flex
-
Overflow for visible (hidden, auto, scroll)
-
-
The application of the landing
- Resolve margin overlap: When margin overlap occurs between parent and child elements, the solution is to create a BFC for child or parent elements
- The BFC area does not overlap with the float area (clear float principle: when calculating the height of the BFC, consider all the elements contained in the BFC, including the float element;)
- Column layout: float on one side, BCF on the other side takes up the remaining space (float box area does not superimpose on BFC;)
From: juejin. Cn/post / 684490…
The box – sizing box model
- box-sizing:content-box; By default, only the width of the content is counted; border and padding are not counted within width
- box-sizing:border-box; Border and padding are computed within width
- box-sizingpadding-box; Padding is computed within width
CSS variable
// Defined in this pseudo-class to ensure that all selectors are accessible:root{
--red: #ff0e0e; // The variable name must be case-sensitive at the beginning --tiny-shadow:4px 4px 2px 0 rgba(0.0.0.0.8); } / / useli {
color:var(--red,red); // The second optional argument is used when the first argument does not take effect (alternative)box-shadow: var(--tiny-shadow);
}
Copy the code
CSS variables are useful for managing colors, switching themes, reducing repetitive code, and increasing readability
Among other CSS variables, the calc() function can also be used
Commonly used unit
-
Px: unit of pixels
-
The percentage % :
-
Em: Font size relative to the element
-
Rem: When applied to non-root elements, is the font size relative to the root element (root EM)
-
Vh /vw:v stands for view, 100vh is 100% window height
Pseudo classes and pseudo elements
Pseudo elements
- ::fist-line adds styling to the first line of text for an element
- ::first-letter Adds style to the first letter or word of an element’s text
- ::before Inserts something before an element
- ::after Inserts something after an element
- :: Selection Styles the element selected by the cursor
pseudo-classes
-
:link
- If you select a hyperlink element that has not been visited, any link that has been clicked will change color to indicate which link has been visited. This attribute is used to represent links that have not been visited
-
:visited
- In contrast to the former, it is used to mark which links have been visited and prevent repeated clicks
-
:hover
- Select the element over which the mouse hovers, often used on the PC side, when the mouse is over an element style, the mobile side is basically not used
-
:active
- Select the element in the dot and use it to mark the style of the manipulation feedback when you want the button to have feedback
- It’s not just for buttons
-
:focus
- Elements in focus are usually identified by input tags
-
:empty
- Select an element that has no child elements, such as an empty SPAN
- Note that whitespace is not null and will not be selected by this pseudo-class
-
:checked
- Selecting checked input elements only applies to radio/checkbox
-
:disabled
- Select the disabled form element
-
:only-child(select only child element)
-
:not
- The pseudo class itself has no priority
- The priority is determined by what is inside the parentheses
-
:first-child Matches the first child of the parent element
-
:last-child Matches the last child of the parent element
-
:nth-child() matches the NTH child of the parent (n can be a number, a keyword, or a formula)
- All rows are selected with n
- If the parameter is n+ I, the following items are selected from the ith line. For example, if n+3 is selected from the third line, the following items are selected
- If the parameter is -n+ I, the first I elements are selected. For example, -n+6 indicates the first six elements
- 2n means multiples of 2 rows are selected, even rows are selected
- 2n+1 indicates that odd rows are selected
- 3n indicates that every three rows are selected once
- Odd means odd, even means even
-
:nth-last-child(n) matches the next-to-last sibling element
-
:nth-of-type(n) matches the NTH sibling of the same type
-
: root root element
Link: juejin.cn/post/684490…
Common selector
By weight! Important has the highest priority, followed by inline styles
- Id selector (# myID)
- Class selector (.myClass)
- Attribute selector (a[rel=”external”])
- Pseudo-class selectors (:link, :visited, :active, :hover, :before, :after)
- Tag selector (div, H1, P)
- Adjacent selector (H1 + P)
- Child selector (UL > LI)
- Descendant selector (Li A)
- Wildcard selector (*)
From: juejin. Cn/post / 684490…
Inline inline-block Specifies the difference between blocks
- block:
- Block elements will have an exclusive row, and multiple block elements will each have a new row. By default, the width of the block element automatically fills its parent element width.
- Block elements can set width and height. Block-level elements, even with their widths set, still occupy a single row.
- The block element can set margin and padding properties.
-
inline-block:
Simply put, the object is rendered inline, but the contents of the object are rendered as a block object. Subsequent inline objects are arranged in the same line. For example, we can give a link (element A) inline-block property value that has both the width and height properties of the block and the inline line properties.
-
inline:
- An inline element does not monopolize a row. Multiple adjacent inline elements are placed in the same row until there is no more of them, and a new line is replaced. The width varies with the content of the element.
- The inline element sets width, and the height property is invalid.
- The padding and padding properties of inline elements, horizontal padding-left, padding-right, margin-left, margin-right all generate margin effects; But vertical padding-top, padding-bottom, margin-top, margin-bottom doesn’t produce margin effects.
Note: Some inline elements that are also substitutable elements, such as img\input, carry a width height attribute, so you can set the width and height
Homyeeking Link: juejin.cn/post/684490…
The transition and animation
The transition:
Syntax: Transition: CSS properties, time spent, effect curve (default ease), delay time (default 0)
What it does: Adds an overshoot effect to changes to an element
Animation:
Syntax: Animation: name of the animation, time spent for one cycle, motion curve (default ease), animation delay (default 0), number of plays (default 1), whether to play the animation backward (default normal), whether to pause the animation (default RUNNING)
@keyFrames animation name {} TODO is required
Display: none, and the visibility: hidden
The former does not retain elements (not rendered) and the position is overwritten by the normal document flow afterwards. Reflow is triggered when a value is changed
The latter will still retain elements, just not visible. Repaint is triggered when a value is changed
Dom tree: display: None and visibility:hidden
Render tree: Visibility: Hidden
Opacity :0 and opacity: hidden are also opacity, but opacity:0 can trigger clicks and other events
Horizontal center
- knownThe width of theElement Settings ofThe textContent level center:
text-align:center
- Set to a widthBlock-level elementsHorizontally centered:
margin:0 auto
display:flex
+justify-content:center
Center the child element horizontally
Vertical center
- knownhighlyElement Settings ofThe textContent vertically centered:
The line - height: height
Or set the parent elementdisplay:table-cell; vertical-align:middle
display:flex
+aligin-items:center
Center the child element vertically
Horizontal + vertical center
- Absolutely centered except
top/left:50%
For external useMargin-top /left: half the height/width
ortransform: translate(-50%, -50%)
To make thecenterInstead of the top left corner centered. .box1 {display: grid; place-items: center; }
The most convenientAchieve horizontal + vertical center.box1 {display: flex; justify-content: center; align-items: center;
} `The second is convenientAchieve horizontal + vertical center- If you want to center more than one of the above elements, grid layouts will center them on a single column and Flex layouts will center them on a single line (default axis is row).
Such as the middle
With Flexbox or Grid layouts, the child elements default to equal heights (Flex :align-items default to stretch).
Remove the floating
If you don’t clear the float of the child element, there may be nothing to support the parent element, causing a high collapse. The best solution is to use pseudo-elements
.clearfix {
zoom: 1; /* For compatibility with earlier versions of IE */
&::after {
display: block;
content: ' ';
clear:both
}
}
Copy the code
Expand the clickable area
Use pseudo-elements instead of main elements to respond to mouse interactions
button{position: relative;/ *... * /
}
button: before {the content:' ';
position: absolute;top: -10px;
right: -10px;bottom: -10px;
left: -10px;
}
Copy the code
BEM naming convention
The naming convention for BEM is easy to remember: block-name__element-name–modifier-name, i.e., module name + element name + modifier name/state.
In general, component names are based on component directory names:
For example, paging components: /app/components/page- BTN /
The module name of the component is page-bTN. All elements within the component must be named with the module name, for example:
<div class="page-btn"> <button type="button" class="page-btn__prev"> </button> <! -... <button class="page-btn__next"> </button> </div>
.header__logo{ border-radius: 50%; } .header__title{ font-size:16px; }
.page-btn__prev--loading{ background:gray; } .page-btn__prev--disabled{ cursor: not-allowed; }
Used in Sass
.header {
&__title {
wdith: 100px;
padding: 20px;
}
&__button {
&--primary {
background: blue;
}
&--default {
background: white; }}}// from https://juejin.cn/post/6969524904400011301#heading-6
Copy the code
CSS interview questions
- Does CSS load block
YES. Although DOM parsing and CSS parsing are parallel, the render tree relies on the DOM number and the CSSOM tree.
Second, since JS may manipulate DOM nodes and CSS styles, js execution must wait for CSS to finish loading.
pseudo-classes
andPseudo elements
The difference between them? Usage scenarios?
Pseudo-elements are similar to pseudo-DOM elements, adding additional effects to a DOM element such as clearing floats or small ICONS.
Before, after, first-line, first-letter
Pseudo-classes are used for special class multiple choice questions and can be retrieved by mouse hover, visited links, or by regular selection
Common ones are hover, first-child, first-child, Visted and so on
Vuejs basis
TODO
Vuejs interview questions
TODO
Webpack basis
TODO
The Webpack compilation project starts by parsing webpack.config.js, invoking the responding hook each time a specific step is completed
loader
plugin
Nodejs basis
NodeJS is a JavaScript runtime environment based on Chrome V8 engine. NodeJS uses an event-driven, non-blocking I/O model, making it lightweight and efficient. And a bunch of optimized API library calls (like c++ ‘s libuv).
The most direct manifestation of Nodejs asynchronous programming is the callback. Make code execution without blocking or waiting for file I/O operations, read the file while executing the next code, improve program performance.
Event loop
Node.js is a single-process, single-threaded application, but supports concurrency through events and callbacks, so performance is very high.
Each API of Node.js is asynchronous and runs as a separate thread, using asynchronous function calls, and handling concurrency.
Almost all of node.js’s event mechanisms are implemented using the observer pattern in design mode.
Node.js single threads are similar to entering a while(true) event loop until no event observer exits, generating an event observer for each asynchronous event and calling the callback if an event occurs.
Author: Front-end development Xiao Ma Ge link: juejin.cn/post/690109…
other
TODO
Principles of browsers
TODO
HTTPS
TODO
reference
JS – The way to front-end interview- caibaojian.com/interview-m…
Js often meet questions summary – big factory interview question of the day