The point of this article is to review the basics. It covers js basics,CSS, new ES6 features and a summary of array methods. Without further ado, summarize some interview questions. For your convenience. Cover as many basic interview questions as possible
I. JS foundation.
1. Data type:
- Raw data type:
Number.String.Boolean,
Null,
Undefined,
Symbol(ES6, unique value), BinInt,(ES10, built-in object, can represent arbitrarily large integers)Copy the code
- Reference data types:
Object contains Array,Function,date...
2. Judgment of data type
- Typeof for primitive data types, the normal type is displayed except for special NULL. Here are a few different chestnuts
console.log(typeof 5) // number
console.log(typeof null) // object
console.log(typeof []) {} fun() // object
- Instanceof can correctly determine the type of the object, mainly by judging the prototype chain of the object is always not able to find the type of prototype, note that the judgment is the object!!
console.log('string' instanceof String) // Returns false, not an object instance, so returns false
console.log(new String(a)instanceof String) // true
console.log({} instanceof Object) // true
console,log([] instanceof Array) // true
Copy the code
Is this the end of it? It seems to be somewhat different from our work, in the work often need to judge the data do not know what type and want to know. So here’s what I’m going to say
Object. The prototype. ToString. The call Object prototype method toString (), in the use of the call, basically can accurately check the data types, please see below chestnuts
const toStr = Object.prototype.toString
log(toStr.call(new String)); // [object String]
log(toStr.call(Math)); // [object Math]
log(toStr.call([])); // [object Array]
log(toStr.call(null)); // [object Null]
Copy the code
3. Null and undefined
First of all, they are both basic data types and have only one value of their own. Null can be interpreted as an empty object and undefined can be interpreted as an undefined object. Undefined is returned when a variable is declared but not yet defined. Null is used to assign an initial value to a variable that may be an object
Null is not an Object. Typeof NULL outputs Object, but this is a Bug left over from jS history
4. This in js
(1) In the browser, in the global scope, as a common function
- This is equivalent to the window object
- A variable declared with var is equivalent to adding an attribute to window. This also refers to window
console.log(this= = =window) // true
val str = 'hello'
console.log(this.str) // hello
console.log(window.str) // hello
Copy the code
Var fn = new Function(); var fn = new Function();
(3) Explicit binding (the first argument executed by call,apply,bind)
- Whether the function is called by call,apply,bind, and if so, this is bound to the specified object
function fn() {
console.log(this.a)
}
var obj = {
a: 'fff'
}
fn.call(obj) // fff
Copy the code
(4) Implicit binding is used as an object attribute (the object calling the attribute)
- For this reference in functions, it’s useful to say that at runtime this always refers to the object that last called it… If the function is called from a context object, this refers to that context object
var a = 'hello'
function fn () {
conole.log(this.a)
}
var obj = {
a: 'I'm a in obj'.
fn: fn
}
var b = obj.fn
fn() // hello
b() // I am a in obj
Copy the code
5. The process of new an object
var a = new Foo()
- Create a new object
- Set this object’s prototype to Foo,a.proto = foo.prototype
- Bind this to this object
- Finally, the new object is returned
6. Scopes and closures
Understanding scope
- Free variables
- Scope chain, and free variable look-up, can’t find a step up look-up
- closure
A closure is a function that has access to variables in the scope of another function. The most common way to create a closure is to create another function within a function that has access to local variables of the current function
-
Closure scenario
(1) Function is passed as a variable variable
(2) function as return value
Closures in actual development
function fn(){
var n = 0;
function add(){
n++;
console.log(n);
}
return add;
}
var a1 = fn(); // Note that the function name is just an identifier (a pointer to the function), and () is the executing function;
a1(); / / 1
a1(); //2 The second call to n is still in memory
Copy the code
7. Prototypes and prototype chains
Five rules to remember for prototyping
- All application types can add custom attributes
- All references have their own implicit archetypes (
__proto__
) - Functions have their own explicit prototype
- All implicit stereotypes of reference types point to explicit stereotypes of the corresponding constructor
- When a custom property of a reference type is used, the property of that reference type is removed if the property is not available
__proto__
To look for in
7. What are the three stages of the JS event
- Event capture phase
When we do something at a node in the DOM tree (click, mouse move, etc.), we emit event after event, which is emitted from the window and continues through the lower nodes to the target node of the division. This process is the event capture phase
document --> html --> body --> div
- Event target stage
The event is emitted on the target as the event is passed through to the target node. That’s the goal phase
- Event bubbling phase
Event bubbling is propagated from the target node and up the hierarchy. (We usually use the event binding of the parent node to use the principle of event bubbling.)
div --> body --> html --> document
W3C: When any event occurs, event capture starts from the top level until the event trigger reaches the event source, and event bubbling up from the event source
Methods to prevent event propagation:
In W3C, cancelBubble = true is used in IE using the stopPropagation() method
Prevent default behavior:
In W3C, use the preventDefault() method to return false in iE
8. What built-in functions do you know in JS
Object, Array, Boolean, Number, String, Function, Date, RegExp, Error, parseInt, parseFloat, Math
9. What’s the difference between var, let and const
Var declaration variables are global variables that are mounted on Windows. Var can declare variables of the same name. Variables declared by let and const are local scoped. Variables with the same name cannot be declared and will not be promoted
var a = 10
log(a,window.a) / / 10 10
if(true) {
var a = 20 // var Variable promotion
let b = 10
}
log(a) // 20 // var
log(b) // Error is not defined
log(c) // error: let does not have variable promotion
let c = 200
var a = 10
log(a) / / 10
var a = 100
log(a) // 100 // var can declare variables with the same name
const a = 10
const a = 100
log(a) / / an error
Copy the code
10. Shallow and deep copies
Shallow copy: refers to copying only references to objects. Multiple objects point to the same address in the heap. If you modify one object, the others will change
var obj = {
a: 10.b: 20
}
varobj1 = {... obj} obj.a =200
log(obj) // {a:200,b:20}
log(obj1) // {a:200,b:20}
Copy the code
Deep copy: To make a full copy of an object from the heap, creating a new area of the heap for storage, and the modification does not affect the original object
Parse (1) json.parse (), this can also be used in explicit work, but note that it ignores undefined, symbol, and circular references
(2) Object.assign({},obj), cannot handle multiple layers of nesting (3Shallow copy plus recursion// Define a deep-copy function that takes the target argument
function deepClone(target) {
// Define a variable
let result;
// If it is an object that needs a deep copy
if (typeof target === 'object') {
// If it is an array
if (Array.isArray(target)) {
result = []; // Assign result to an array and iterate
for (let i in target) {
// Recursively clone each item in the array
result.push(deepClone(target[i]))
}
// Determine if the current value is null; Directly assign to null
} else if(target===null) {
result = null;
// If the current value is a RegExp object, assign it directly
} else if(target.constructor===RegExp){
result = target;
}else {
// If the object is a normal object, the direct for in loop assigns all the values of the object recursively
result = {};
for (let i intarget) { result[i] = deepClone(target[i]); }}// If it is not an object, it is a primitive data type
} else {
result = target;
}
// Return the final result
return result;
}
Copy the code
11. Anti-shake and throttling
First, think about the situations in which we use anti-shake and throttling functions in real development. The input listens for keyUP events, listens for Scroll events, and frequently clicks events. Anti-shake: refers to the frequently triggered call action that is executed last. The callback is executed n seconds after the event is triggered. If the event is triggered again within n seconds, the timer is reset and the callback is executed only if the event is not triggered within n seconds
function bedounce(fn,delay = 500) {
var timer = null
return function() {
var self = this, arg = arguments
if (timer) {
// To exist is to reset the timer
clearTimeout(timer)
timer = null
}
timer = setTimeout(() = > {
fn.apply(self, args)
}, delay)
}
}
Copy the code
Throttling: Function events triggered by high frequency can be triggered only once in a certain period of time to reduce the number of functions triggered.
function throttle(fn, delay = 500) {
var timer = null
return function() {
var self = this, args = arguments! timer && timer =setTimeout(() = > {
fn.apply(self, args)
timer = null
}, delay)
}
}
Copy the code
2. CSS basics.
1. The box model
A box model is essentially a box, consisting of margin, border, padding and actual content
- Standard box model: Width is the content width
- Weird box model (IE): Width is content+padding+border
2. Which properties in the CSS are inheritable
- Font related attributes
font-weight
font-size
font-style
...
Copy the code
- Text-dependent attributes
Text-align text-shadow Text-align text-shadow text-align...Copy the code
- The element is visible
visibility
- The cursor attributes
- cursor
3. Priority of the CSS selector
! Important > Inline Style > ID selector > Class selector = Pseudo-class selector = Attribute selector > Element selector = pseudo-element selector > Wildcard selector = descendant selector = sibling selector
There is also the question of weights
10000: !important
1000: Inline/outgoing style100: ID selector10: class/pseudo-class/attribute selector1: element/pseudo-element selector0: Wildcard/descendant/sibling selectors inherit styles without weightsCopy the code
4. How to hide elements in CSS
Visibility: Hidden elements, but will not change the layout or trigger eventsdisplay: None Hides elements and changes the layout of the page z-index: -1The hierarchy is placed below other elementsopacity: 0Opacity to0The page layout does not change, and binding events can still be triggeredCopy the code
5. Animation attributes
Animation-name specifies the keyframe name that needs to be bound to the selector. Animation-duration specifies the events that will take to complete the animation, calculated in seconds or millisecondsfunctionSpecifies the speed curve of the animationanimation-delaySpecifies the delay before the animation beginsanimation-iteration-countSpecifies how many times an animation should playanimation-directionSpecifies whether the animation should take turns playing backwardsCopy the code
Js achieve animation way: setInterval, requestAnimationFrame
6.CSS implements animation
Transition – How do property values for setting styles smoothly transition from one state to another
Transform is used for 2D or 3D transformations of elements and can be used to change the shape of elements. Rotate, scale, skew,translate,matrix. Usually used in combination with transition
7. The way to center the box vertically and horizontally
- Absolute + negative margin (given width and height of box)
.parent {
position: relative;
}
.child {
width: 200px;
height: 200px;
position: absolute;
left: 50%;
top: 50%;
margin: -100px 0 0 -100px;
}
Copy the code
- Absolute + margin:auto
.parent {
position: relative;
}
.child {
position: absolute;
left: 0%;
top: 0%;
right: 0%;
bottom: 0%;
margin: auto;
}
Copy the code
- Absolute + transform
.parent {
position: relative;
}
.child {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
Copy the code
- Display: flex I don’t know the box width and height, not compatible with IE lower version)
.parent {
display: flex;
justify-content: center;
align-items: center;
}
Copy the code
- Display: table-cell (for table)
.parent {
display: table-cell;
text-align: center;
vertical-align: middle;
}
Copy the code
- display: grid
.parent {
display: grid;
}
.child {
align-self: center;
justify-self: center;
}
Copy the code
8. Mobile adaptive REM
Rem is a unit of length that changes the font size relative to the HTML root element to assist media queries
Js encapsulates the REM scheme
export function rem (doc, win) {
let docEl = doc.documentElement; // Consider compatibility and screen rotation events
let resizeEv = 'orientationchange' in window ? 'orientationchange' : 'resize'
let recalc = function () {
var clientWidth = docEl.elientWidth
if(! clientWidth >=750) {
docEl.style.fontSize = '100px'
} else {
docEl.style.fontSize = 100 * (clientWidth / 750) + 'px'}}if(! doc.addEventListener)return
win.addEventListener(resizeEv,recalc,false) // Screen size and rotation changes are adaptive
doc.addEventListener('DOMContentLoaded', recalc, falseAdaptive recalc()}Copy the code
Rem adaptor portal
9. CSS preprocessor (LASS, SASS) differences
- Define variables
Sass is a variable defined starting with $
$mainFontSize: 14px;
Less is a variable defined beginning with @
@mainFontSize: 14px;
- scope
Sass has no local variables. Variables defined in {} in LESS that meet the nearest principle are local variables
- Hybrid (Mixins)
Sass blending: The @mixin command is used to declare Mixins in the SASS style, and the @include command is used to call defined Mixins in the selector
@mixin mixinFn($bg-c:red) { // Declare mixins to be called mixinFn
width: 50px;
height: 50px;
background-color: $bg-c;
}
.isA { 调用Mixins
@include mixinFn(); // No parameters
}
.isB {
@include mixinFn(blue); // Add parameters
}
Copy the code
Less blending: To add another defined class to a defined classA
.mixinFn($bg-c:red) { // Declare mixins to be called mixinFn
width: 50px; height: 50px; background-color: $bg-c; }.isa {call mixins.mixinfn ();// No parameters
}
.isB {
.mixinFn(blue); // Add parameters
}
Copy the code
- inheritance
Sass inheritance: @extend
.isA {
margin:5px 20px;
padding: 10px;
}
.isB {
@extend .isA; // Inherit the isA style
color: red;
}
Copy the code
Less inheritance
.isA { // Mixins similar to less
margin:5px 20px;
padding: 10px;
}
.isB {
.isA; // Inherit the isA style
color: red;
}
Copy the code
New ES6 features
1. The block-level scope let and const are proposed
Let is the more perfect var is not a global variable, and generally no variable promotion occurs
Const defines a constant. It cannot be reassigned. If the value is an object, the property inside it can be changed
The difference between let and const and var is familiar. I won’t repeat it here, please look at the next one
2. Template string
Template strings greatly improve the quality and readability of our code, using the ${} form instead of our original data concatenation
- Basic string formatting.
//ES5
var name = 'tt'
log(name + 'ly') // ttly
//ES6
log(`${name}ly`) // ttly
Copy the code
- Use the backslash () solution to do multi-line string concatenation
//ES5
var str = "hello \
world"
// ES6
let str = `hello
world`
Copy the code
3. The deconstruction
- An array of deconstruction
// ES5
var arr = [1.2.3]
var a = arr[0]/arr[1]/arr[2] // Use an index
// ES6
const arr = [1.2.3]
const[A, A1, A2] = ArR has more gameplay to explore on your ownCopy the code
- Object to deconstruct
Objects are matched by attribute names instead of arrays that use variable object elements. If the match is not successful, the variable will be undefined. You can also alias the variable during deconstruction
const obj = {
name: "ttly"
age:18
}
const { name1, arr, age: a } = obj
log(name1, arr, age) // ttly ,undefined, 18
Copy the code
4. Expand operator “…”
. Not only can it be used as a residual operator, but it can also be used to expand the array…. You can pass each item of the array into a function at once
// ES5
var arr = [1.2.3]
console.log.apply(console,arr)
// ES6
const arr [1.2.3]
console.log(... arr)Copy the code
5. Object extension method
- The object.assign () method is used to assign the values of all enumerable attributes from one or more source objects to the target Object, returning the new Object. If a property in the target object has the same key as the source object, the target object is overwritten
Grammar: Object. The assign ({},... obj)
const target = {a: 1.b: 2}
const source = {b: 5.c: 6}
const newTarget = Object.assign(target,source)
log(target) // a: 1, b: 5, c: 6
log(newTarget) // a: 1, b: 5, c: 6
Copy the code
- The object.is () method checks whether two values are the same and returns a Boolean value
Object.is('foo'.'foo'); // true
Object.is(window.window); // true
Object.is('foo'.'bar'); // false
Object.is([], []); // false
var foo = { a: 1 };
var bar = { a: 1 };
Object.is(foo, foo); // true
Object.is(foo, bar); // false
Object.is(null.null); // true
/ / special case
Object.is(0, -0); // false
Object.is(0, +0); // true
Object.is(-0, -0); // true
Object.is(NaN.0/0); // true
Copy the code
6.Set
Set is a new data structure introduced in ES6 that is similar to Array. The members of a Set instance are unique and do not duplicate. Arrays can be easily de-duplicated using this feature
const numbers = [2.2.3.3.4.5.6.7.8.8.9.9]
log([...new Set(numbers)]) / /,3,4,5,6,7,8,9 [2]
Copy the code
7. Arrow function ★★★
Core upgrades for ES6…
- Arrow functions do not have their own this, which points to the object where the function was defined. That is, the this reference to the context at definition time
- Arrow functions cannot be used as constructors and cannot be instantiated without their own this
- There is no Argunments in the arrow function. Also because there is no this of its own
- Arrow functions can be assigned by default. Prior to ES6, function parameters could not be assigned by default, but could only be assigned by workarounds inside functions.
- You must declare functions in the same way you define variables
- You can abbreviate it by omitting the parentheses when the function takes only one parameter. When the function body has only one (return) statement, you can omit the braces
function fn(x, y = 'ttly') {
log(x, y)
}
fn(1) // 1, ttly
/ / short
const fn1 = num= > num + 1
Copy the code
8. Class and constructor ★★★
ES6 classes can be thought of as syntactic sugar for the constructor of ES5 generated instance objects, making object prototyping clearer. Class classes can be inherited through extends
class Student {
constructor(name) {
this.name = name
}
si() {
log('hello')}}class ttly extends Student {
constructor(name,age) {
super(name)
this.age = age
}
statis study() {
log('agg')}sayHi() {
super.si()
}
}
Copy the code
Here’s the difference between a Class Class and a constructor
- All methods of the Class Class are not enumerable; the Prototype method in the constructor is enumerable
- The Class Class does not have variable promotion
- Constructors defined by the Class Class cannot be called without using new
- Parent.call(this) : Parent (); Parent () : Parent (); Parent () : Parent ()
9. Promise u u u
Promises were invented to solve the callback hell of asynchronous programming. Promises are simply a container that holds the result of an event (usually an asynchronous operation) that will end at some future date
Promise has three states
- Pending
- Fulfilled (successful)
- Rejected (failure)
Once the promise changes, it will not change. There are only two possibilities :pending-> depressing, and pending-> Fulfilled
Disadvantages: First, you can’t cancel a Promise. Once it’s made, it’s executed immediately. Second, if you don’t set the ruin function, errors thrown internally by a Promise won’t be reflected externally. Also, when in a pending state, there is no way to know what stage of progress is currently in (just started or nearly completed)
const promise = new Promise(function(resolve, reject) {
if (/* Asynchronous operation succeeded */) {
resolve(val)
} else {
reject(error)
}
})
Copy the code
Cheat sheet a handwritten promise implementation
function myPromise(constructor) {
let self = this
self.status = "pending" // Define the initial state
self.value = undefined // Determine the resolved state
self.reason = undefined // Define the state of the rejected state
function resolve(value) {
// Two ==="pending", save state changes are irreversible
if (self.status === 'pending') {
self.value = value
self.status = 'resolved'}}function rejected(reason) {
if (self.status === 'pending') {
self.reason = reason
self.status = 'rejected'}}// Catch a construction exception
try {
constructor(resolve, reject)}catch(e) {
reject(e)
}
}
// Define the.then method for chain calls
myPromise.prototype.then = function(onFulfilled, onRejected) {
let self = this
switch (self.status) {
case "resolved":
onFullfilled(self.value)
break;
case: "rejected":
onRejected(self.reason)
break;
default}}Copy the code
- The promise.all () method is used to wrap multiple Promise instances into a new Promise instance
const p = Promise.all([p1, p2, p3])
// The state of p is determined by p1,p2, and p3
This will be a big pity. The return values of P1, P2 and p3 will form an array and be passed to the callback function of P
(1) Reject (p1,p2,p3); reject (p1, P2,p3); reject (P1, P2,p3)
const p1 = new Promise((resolve, reject) = > {
resolve('hello');
})
.then(result= > result)
.catch(e= > e);
const p2 = new Promise((resolve, reject) = > {
throw new Error('Error reported');
})
.then(result= > result)
.catch(e= > e);
Promise.all([p1, p2])
.then(result= > console.log(result))
.catch(e= > console.log(e));
// ["hello", Error: Error]
Copy the code
Promise has a lot more than just a list of examples that you can click on if you’re interested
10.proxy
Proxy can be understood as a layer of interception before the target object. All external access to the object must pass this layer of interception. Therefore, Proxy provides a mechanism for filtering and rewriting external access. A: What do you mean by Proxy? B: It’s a Proxy. Built-in get and set
Because the understanding is not deep enough, so we can find by ourselves, later slowly supplement
4. Array methods summary (carefully remember not afraid to be asked about various array methods)
1, will change the original array method
The.push() method adds one or more elements to the end of the array and returns the new array length
The (2).pop() method removes the last element of the array, reducing the size of the array and returning the deleted value
The.unshift() method adds one or more elements to the header of the array and returns the new array length
(4).shift() removes the first element of the array, then moves all subsequent elements forward one place to fill the hole in the array header, and returns the deleted element
(5).splice(start) method a common method for inserting or deleting elements in an array.
The.sort() method sorts the elements of the array and returns the sorted array.
Sort (fn) takes a function that, by default, sorts the elements in the array to a string and then compares them to UTF-16Sequence sorting of unit values.const arr = [1.20.5.32.1000]
log(arr.sort()) // [1, 1000, 20, 32, 5]Fn is used to specify the functions to be sorted in some order, and takes two arguments: a the first element to be compared; b the second element to be compared if fn(a, b) is less than0So A will come before B. If f sub n of a, b is equal to0So the relative positions of a and b remain the same if f sub n of a, b is greater than0Then B will come before A.3.4.5.10.1].sort((a, b) = > a - b) / /,3,4,5,10 [1]
Copy the code
The (7).reverse() method reverses the order of the elements in the array and returns the array in reverse order
2, do not change the original array method
(1).slice(start,end) returns a shallow copy of a portion of the array from start to end (not including end) into a new array and returns. It doesn’t change the original array
The (2).join() method converts all elements in an array to a string and returns a concatenated string of new array elements. The argument accepts a string as a delimiter. Defaults to ‘,’ and can be used for simple array flattening
The (3).toString() method converts each element of the array to a string and returns a ‘,’ delimited string. Can be used for simple array flattening
(4).concat() is used to merge two or more arrays. And returns a new array. Note that the concat() method is only a shallow copy. So both the original array and the new array reference the same object, and the old and new objects are modified, and both will change
The.isarray () method checks whether the element is an Array and returns a Boolean
Array traversal, mapping, filtering and other methods
The.foreach () method iterates through the array, calling the specified function forEach element. Note that the forEach() method cannot exit the loop, and the return can only exit the local callback for the next callback. If you want to terminate early, you can use the try block and throw an exception. If you want to change the array, use the third parameter
(2) the.map() method creates a new array and returns a new array for each element after executing the specified function. Note that the map() method creates a new array and consumes memory if the value returned by the specified function is not used. So we should use forEach()
(3).filter() method is used to screen out the judgment method conforming to the specified function. The array returned is the new array after the specified function is called.
(4) the.every() method is used to check whether each element in the array matches the conditions of the specified function. Return true if all elements of the array return true, otherwise return false
(5).some() checks if there is an element in the array that matches the specified function, returning true if there is, and false otherwise
(6) the.reduce() method takes a function as an accumulator, and each value in the array (from left to right) starts to shrink and eventually returns a calculated value. Reduce () does not perform a specified function for empty arrays, but is usually used for summing
Where does the indexOf(element, startIndex) method start to find the position of an element in the array? If it exists, return the indexOf the first position, otherwise return -1
[1.2.3.4.2.4.5].indexOf(2) / / 1
[1.2.3.4.2.4.5].indexOf(4.4) / / 5
Copy the code
(8).lastIndexof () is the same as indexOf() except that the index is queried from the tail to the head. Neither changes the original array
The.find() method is used to determine if there are any elements in the array that match the specified function, and if so, returns the value of the first element that matches the condition. Otherwise return undefined (new in ES6)
The.findIndex() method is used to determine if there are elements in the array that match the specified function. If there are elements in the array that match the specified function, the index value of the element is returned. Otherwise, -1 is returned.
The keys() method is used to create an iterable from an array containing the array keys.
The values() method is used to create an iterable from an array that contains the values of the array.
The (13).include() method checks to see if the specified value exists in the array. Return a Boolean for simple arrays (ES7)
In fact, most of what is recorded here is not my own summary. It was also edited with reference to many excellent articles. While writing, I deepened my own understanding of these basic knowledge. There are also a lot of questions that I did not understand through this summary, so I would like to thank these leaders for their analysis and sharing. It’s also a way for me to learn. I hope you will have a good harvest. Also please do not spray
Array of eighteen martial arts
Js base from shallow to deep