Keep updating ing ~

  • Github address of the front-end infrastructure.README.mdYou can download it totypora(Github’s shortcut to create markdown directory is not practical, so we may try to create a post later, so we will not do relevant processing for the time being)
  • Front-end base Gitbook address.README.mdWill update the progress content in real time.gitbookConsider the whole study after finishing finishing, and then go to the unified processing release, please look forward to!gitbookVersion can be recommended later fragmentation time for review.
  • Front-end basic CSDN address.CSDNBlog postFront end self-cultivation advancedIn, will also be a real-time update of the relevant knowledge points.
  • Front end foundation 1 nuggets address, front end foundation 2 nuggets address

⭐️ is the best encouragement oh wink ~ 💗

4.27

html5

  • Label semantics

    • The right label does the right thing
    • Classification of labels:
      • The massive label
        • An exclusive line
        • Example: div, h1-h6, hr, table, form, p, li, dl, dt
      • Inline tags
        • Example: span, a, img
      • Inline block label
        • Example: the input
  • Audio and video

    • Changed the traditional Flash playback, the use of video and audio
  • WebGL/Canvas etc animation rendering

  • Websocket:

    • Change the traditional long polling mode

css3

  • The box model

    • Standard box model
      • Width and height refer only to the content part, excluding the padding, border, and margin parts
    • IE Box Model (Weird box model)
      • Width and height include margin, border, and padding boxes
    • We usually use the standard box model, but we can set it if we need to use the IE box model in some casesbox-sizing:border-box
  • Horizontal middle implementation

    • Use the positioning
    .container{ position:relative; } .box{ width:200px; height:200px; position:absolute; left:50%; top:50%; margin-left:-100px; margin-right:-100px; } // or. Box {position:absolute; left:50%; top:50%; transformX:-50%; transformY:-50%; }Copy the code
    • Using flex
    .container{
      display:flex;
      justify-content:center;
      align-item:center;
    }
    Copy the code
    • Use the table
    .container{
      display:table-ceil;
      text-align:center;
      vertical-align:middle;
      width:500px;
      height:500px;
    }
    .box{
      display:inline-block;
    }
    Copy the code
    • Using JS control
  • Responsive layout

    • The holy grail layout
      • Using position positioning and floating and negative margin to achieve
    • Twin wing layout
    • Flex implements the Holy Grail layout
.container{ display:flex; flex-direction:row; justify-content:space-between; } .left{ height:200px; flex:0 0 200px; // Zoom ratio 00, width 200px}. Center {flex:1; // Or use flex-grow}. Right {height:200px; flex:0 0 200px; }Copy the code

The layout scheme

  • Media Media Query
    • Suitable for a set of code multi – end adaptation
  • Rem works on mobile
  • Vm/VH percentage layout
  • flex

Z – the principle of the index

  • Takes the element out of the document flow
  • Other ways to get elements out of the document flow:
    • floating
    • positioning
    • transform
    • CSS 3 animation

Which of the following has the highest rendering performance, regardless of other factors

A {} a{}Copy the code

Method two: because the browser’s rendering mechanism makes the search from right to left

Js data type

  • Basic types:
    • number
    • string
    • boolean
    • null
    • undefined
  • Reference types
    • object
    • function
  • Special type
    • Symbol

Several ways to determine data types

  • typeof
  • instanceof
  • constructor
  • Object.prototype.toString.call

4.28

Stack memory, closure scope

let a = {},b = '0',c = 0; A [b] = '* *' a [c] = 'bill' console, log (a [b]) / / billCopy the code

Object, numeric property names are the same as string property names, and arrays are special strings

Extension: The difference between objects and arrays

let a={}, b=Symbol('1'), c=Symbol('1'); [b] = '* *'; A [c] = 'bill'; console.log(a[b]); / / zhang SANCopy the code

Symbol creates unique values that are not equal. The property name of the object does not have to be a string. If it is a number and a string, it is the same value because the index is a string. Object property names can be null, Symbol, undefined, and so on. Reference type values are stored retrograde as strings.

Extension: Implement a Symbol yourself

let a={}, b={n:'1'}, c={m:'2'}; [b] = '* *'; A [c] = 'bill'; console.log(a[b]); / / li siCopy the code

B, c will be converted to a string when used as a reference, and the Object will be converted to a toString, so that is Object Object

Development: the Object. The prototype. The toString project application, with the valueOf with toString distinction (compile order)

The base type is stored directly, the reference type is put in the heap, and finally the address is copied to the value.

As soon as the page is loaded, it forms a stack memory. Each function execution is called squeezing an execution context onto the stack.

Null, and undefined

// Execute the function immediately. But I is not destroyed because I is occupied. Var test = (function(I){return function(){alert(I *=2); var test = (function(I){alert(I *=2); // If there is no I, look in its parent scope. Where the parent scope is created is who}})(2); test(5); // String 4. There are no parameters in test.Copy the code

The output of alert is converted to a string.

var a=0, b=0; function A(a){ A=function(b){ alert(a+b++); }; alert(a++); } A(1); //"1" A(2); / / "4"Copy the code

Note: a++ is calculated with others, and then accumulates 1; Plus plus a adds 1 to itself, and then you add it to somebody else.

Process explanation:

1, GO global: initialize a = 0, b = 0, a a method, reference address, here temporarily marked as AAAFFF000

A(1) = function (1); Alert (A ++); alert (A ++); alert (A ++); alert (A ++); alert (A ++) So what’s alert is 1 before it’s added

3. Continue to execute A(2), then the function referred to by A is BBBFFF000 after the change, and the parameter b passed in at this time is 2, and A is in its upper scope. It can be seen from Step 2 that it is 2 after superposition, so the alert output should be 2+2. String 4 (alert is automatically converted to toString)

let a = 1;
console.log(5+a++);	//6
console.log(a)	//2

let b = 1;
console.log(5+(++a));	//7
console.loog(a)		//2
Copy the code

Closures: Save, protect

Depth and light copies of objects and arrays

let obj = { a: 100, b: [10, 20, 30], c: { x: 10 }, d: /^\d+$/ }; let arr = [10, [100, 200], { x: 10, y: 20 }]; //=> function deepClone(obj) {if (typeof obj! == "object") return obj; if (obj instanceof RegExp) return new RegExp(obj); if (obj instanceof Date) return new Date(obj); let cloneObj = new obj.constructor; for (let key in obj) { if (obj.hasOwnProperty(key)) { cloneObj[key] = deepClone(obj[key]); } } return cloneObj; }Copy the code
  • Shallow copy: Copies only the first layer. You can still change the first layer by manipulating the second layer. It is a shallow copy, only references are copied
let obj = { a: 100, b: [10, 20, 30], c: { x: 10 }, d: /^\d+$/ }; Let obj2 = {} for(let key in obj){// obj.hasownProperty (key), true is private, false is not private. If (!) {if(!) {if(!); obj.hasOwnProperty(key))break; Obj2 [key] = obj[key]} //ES6 let obj3 = {... obj}Copy the code
  • Deep copy :(recursive/string conversion)
// JSON.stringify&JSON.parse let obj = { a: 100, b: [10, 20, 30], c: { x: 10 }, d: /^\d+$/ }; let obj2 = JSON.stringify(obj); / / "{" a" : 100, "b" : [10, 30], "c" : {10} "x" :, "d" : {}} "obj2 = JSON. Parse (obj2)Copy the code

Json. parse This approach has drawbacks: regex, functions, dates, symbols, etc., can be problematic

Function deepClone(obj){// let newobj = new obj.constructor; Or {}; // If (typeof obj === null)return null; // If (typeof obj === null)return null; if(typeof obj ! == "object")return obj; if(obj instanceOf RegExp){ return new RegExp(obj) } if(obj instanceOf Date){ return new Date(obj) } let newobj = new Object(); For (let key in obj){if(obj. HasOwnProperty (key)){newobj[key] = DeepClone (obj[key])}} return newobj; }Copy the code

Exclusions: NULL, Date, regular RegExp, and not object

object-oriented

function Foo() { getName = function () { console.log(1); }; return this; } Foo.getName = function () { console.log(2); }; Foo.prototype.getName = function () { console.log(3); }; var getName = function () { console.log(4); }; function getName() { console.log(5); } Foo.getName(); //2 getName(); //4 Foo().getName(); //Foo() ordinary function execution; GetName = -> 1 and return this, where this refers to window. Window.getname 1 getName(); //1 new Foo.getName(); // With no argument new, the dot approach is called member access. Foo().getName(); new Foo().getName(); // new Foo, getName. 3 new new Foo().getName(); // Priority new (new Foo()).getName().getName, first new Foo() creates an instance Foo, which becomes new foo.getName(), which becomes first member access, the method on the prototype, which outputs 3, becomes new 3, which is 3 note: If the parameter new is the first to execute new, then the parameter new and the member access two levels of the same level. Foo AAAFFF0000 getName = func -> 5 // Foo is a heap, Foo is still an object, We have prototype (also a reference type and also a heap), length, and then we add a getName attribute to it; GetName = func -> 4 getName = func -> 4Copy the code

Variable promotion: Var function is defined and assigned before all code is executed

Synchronous asynchronous EventLoop

async function async1() {
    console.log('async1 start');
    await async2();
    console.log('async1 end');
}
async function async2() {
    console.log('async2');
}
console.log('script start');
setTimeout(function() {
    console.log('setTimeout');
}, 0)
async1();
new Promise(function(resolve) {
    console.log('promise1');
    resolve();
}).then(function() {
    console.log('promise2');
});
console.log('script end');


script start
async1 start
async2
promise1
script end
async1 end
promise2
setTimeout

Copy the code

Browsers are multi-threaded, js is single-threaded. Time queue EventQueue. Microtask queue, macro task queue. The main thread code executes first.

Timers, event bindings, Ajax are macro tasks, async, await, Promise, etc are micro tasks

4.29

  • Question 1:
function A(){ alert(1); } function Func() { A=function(){ alert(2); }; return this; } Func.A=A; Func.prototype={ A:()=>{ alert(3); }}; A(); Fn.A(); Fn().A(); new Fn.A(); new Fn().A(); new new Fn().A(); // Note the last one, arrow functions cannot be new, because arrow functions have no prototype chain and therefore no constructorCopy the code
  • Question 3:
var a = ? ; if (a == 1 && a == 2 && a == 3) { console.log(1); }Copy the code

Two equals signs convert data types to equal values, and three equals must be absolutely equal

Double etc.

  • Object == string object toString becomes a string, then a number, compare; [10] = = 10
  • Null == undefined but does not want to wait like the others
  • NaN and nothing wanted to wait
  • The rest is converted to numbers. eg.'1'==true

1. Use toString

Since two equal signs are compared, one is a number, and we assume that a is object (for example,[1],[2],[3], arrays are special objects), the comparison must be performed in a way that toString is converted to numbers for comparison. So we can play around with toString, modify its toString

var a = { i:0, toString(){ return ++this.i; }} // Perform toString three times, returning 1, 2, and 3 respectively. Var a= [1,2,3] a.tostring = a.hift; The shift method removes the first value of the array and returns the first value. So every time you compare the toString to call a, the values you get are I, 2,3Copy the code

2, using data hijacking get:

Since a is global, the set method that gets A is hijacked globally to modify it

var i = 0; Object.definedProperty(window,'a',{ set(){ return ++i; }})Copy the code

3, or use true

Vue&React

  • React is different from Vue

    • Vue stands for MVVM (two-way data binding).
    • Data changes View changes, view changes data changes
    • React stands for MVC.
    • Vue wrote the form binding event for us, React needs to bind itself
      • React needs to implement the onchange event itself
      • In VUE, v-mode directly helps us to bind data without writing onChange events
    • MVC is different from MVVM
      • MVC defaults implement data changes (one-way data changes)
      • MVVM implements data change view change, view change data change (two-way data change)
      • MVC just lacks an onChange event binding
  • Vue data bidirectional binding 2.0 and 3.0 implementation

    • Vue2.0Object.definedPropertyModify set and get;
    • Vue3.0 throughProxyIntercept set and GET methods for related operations to achieve two-way data binding.

Solutions and implementation principles for cross-domain problems

1, the json

Using script tags

  • Only get requests
    • unsafe
    • Have a cache
    • There is a limit to the size of the data that can be passed
    • Server separate support is required
  • The client
< script SRC = "https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js" > < / script > < script > $. Ajax ({url: 'http://127.0.0.1:8001/list', method: 'get', dataType: 'the json' success: res = > {the console. The log (res); }}); </script>Copy the code
  • The background
let express = require('express'), app = express(); app.listen(8001, _ => { console.log('OK! '); }); app.get('/list', (req, res) => { let { callback = Function.prototype } = req.query; Let data = {code: 0, message: 'test data'}; res.send(`${callback}(${JSON.stringify(data)})`); });Copy the code

2. Iframe-based cross-domain solutions

The primary domain is the same, but the subdomain is different

  • window.name
  • document.domin
  • location.hash
  • post message

3. CORS cross-domain resource sharing

The client

import axios from 'axios'; import qs from 'qs'; Axios. Defaults. BaseURL = "http://127.0.0.1:3000"; axios.defaults.timeout = 10000; axios.defaults.withCredentials = true; /* * Set the format of the requested data transfer (see what format the server requires) * x-www-form-urlencoded */ axios.defaults.headers[' content-type '] = 'application/x-www-form-urlencoded'; axios.defaults.transformRequest = data => qs.stringify(data); /* * Set request interceptor * TOKEN check (JWT) : Receives tokens returned by the server, stores them in vuEX/local storage, and sends each request to the server, We should take token to * / axios. Interceptors. Request. Use (config = > {let token = localStorage. The getItem (" token "); token && (config.headers.Authorization = token); return config; }, error => { return Promise.reject(error); }); Response interceptor * / * * / axios interceptors. Response. Use (response = > {return response. The data; }, error => {}); export default axios;Copy the code

The server

app.use((req, res, next) => { res.header("Access-Control-Allow-Origin", ""; res.header("Access-Control-Allow-Credentials", true); res.header("Access-Control-Allow-Headers", "PUT,POST,GET,DELETE,OPTIONS,HEAD"); res.header("Access-Control-Allow-Methods", "Content-Type,Content-Length,Authorization, Accept,X-Requested-With"); req.method === 'OPTIONS' ? res.send('CURRENT SERVICES SUPPORT CROSS DOMAIN REQUESTS! ') : next(); });Copy the code

4. Implement cross-domain request based on HTTP proxy

Use proxy for development and nginx reverse proxy for deployment

Vue/React framework about component information communication caused by the interview questions

vue

  • Property transfer
  • Publish subscription (EventBus) : on/on /on /emit
  • Provide / inject
  • Slot slot

  • p a r e n t / parent /
    children
  • vuex

react

  • attribute
  • Release subscription
  • React.createContext
  • redux / react-redux / mobix / dva

What are the schemes for component communication

  • Attribute scheme: Parent to child

  • Vue publish and subscribe (child to parent)

    • Property plus publish subscription
  • React returns calls from children to parents

    • Property plus a callback function

Ancestor and descendant communicate: all elements of the descendant element are put into the ancestor, called context

  • Any communication between uses the local storage scheme
    • Localstorage (cookies are limited in size, not of the same magnitude)
    • Redux /vuex (a refresh without; Public state management, local storage, optimization)

The difference between session and cookie

  • If the server sets the session, the information returned by the server to the client will carry set-cookies. The client will set the information in cookies, which can only be read and cannot be changed. When the client requests it again, it takes the cookie with it.

algorithm

Array to heavy
  • set
let ary = [12, 23, 12, 15, 25, 23, 25, 14, 16]; Let arr = [...new Set(ary)]; Let arr = array. from(new Set(ary))Copy the code
  • Traverse the contrast

    • Walk through, open up a new array, no equal pushes into it
    let ary = [12, 23, 12, 15, 25, 23, 25, 14, 16]; let arr = []; for(var i; i<ary.length; I ++){let item = ary[I] let args = ary. Slice (I +1) {}else{arr.push(item)}}Copy the code
    • Iterate, compare with the following, set to NULL, and finally filter out all values of NULL
    let ary = [12, 23, 12, 15, 25, 23, 25, 14, 16]; let arr = []; for(var i; i<ary.length-1; I++){// If (args.indexof (item)>-1){arr[I] = null; if(args.indexof (item)>-1){arr[I] = null; }} ary = ary. Filter (item=>item! ==null) // Filter out nullCopy the code
  • Take each item in the array and store it in a new container. If you don’t have one, you don’t

let ary = [12, 23, 12, 15, 25, 23, 25, 14, 16]; let obj = {} for(var i; i<ary.length; i++){ let item = ary[i]; // If the object does not have this property, it is undefined; You can also use in or object.keys. Not if(typeof obj[item]! == 'undefined'){// Must have this attribute // Replace the last item. Ary [I] = ary[ary.length - 1] ary.length--; i--; continue; } obj[item] = item } obj = {}Copy the code
  • Sort first, then compare next to each other
ary.sort(); / / ascendingCopy the code

5.7

Algorithm to review

Array to heavy
  • ES6 : Set
let ary = [12, 23, 12, 15, 25, 23, 25, 14, 16]; Let arr = [...new Set(ary)] // Use the expansion operator let arr = array. from(new Set(ary)) // Use array. fromCopy the code
  • Compare all items with each following one, and delete if there are duplicates (leave out the last item because there is nothing to compare after it)
let ary = [12, 23, 12, 15, 25, 23, 25, 14, 16]; for(let i = 0; i < ary.length - 1; i++){ let item = ary[i], args = ary.slice(i+1); If (args.indexof (item)>-1){if(args.indexof (item)>-1){if(args.indexof (item)>-1){ // Include (I,1); // Include (I,1); // Include (I,1); i--; // if I ++ is used, the index of each item will be changed. // If I ++ is used, the index of each item will be changed. Ary. Filter (item=>item!); ary. Filter (item=>item! == null) // ary[i] = null; I -- ary[I] = ary[ary. Length-1] ary. Length --; I -- ary[I] = ary. i--; }}Copy the code
  • Object key-value pairs (arrays)
    • Take an item and place it in the empty container, and delete the current item if it has already been stored
let ary = [12, 23, 12, 15, 25, 23, 25, 14, 16]; let obj = {}; for(let i = 0; i<ary.length; i++){ let item = ary[i]; if(typeof obj[item] ! Ary [I] = ary[ary.length-1] ary.length--; ary[I] = ary[ary.length-1] ary.length--; i--; continue; } obj[item] = item; } obj=null; // When obj is finished, the heap currently in use is destroyedCopy the code
  • Sort first, then compare next to each other
    • Adjacent item processing scheme
let ary = [12, 23, 12, 15, 25, 23, 25, 14, 16]; Ary.sort ((a,b)=>a-b) // Sort in ascending order // Method 1: Compare each item with the last one and delete the current item if they are the same. The last term doesn't have the last term, so don't use for(let I = 0; i<ary.length-1; i++){ if(ary[i] === ary[i+1]){ ary.splice(i,1); ary.length--; i--; }} / / second way: you can use the regular ary = ary. Join (' @ ') + '@' / / "@ 12 December 14 15 @ @ @ 16 @ @ 23 @ 25 @ @ 25" let reg = / \ d + @ \ * / g / 1 / \ d to get the number. Replace (reg,(val,group1)=>{arr.push(Number(group1.slice(0, group1.leng-1)))}) conole.log(arr)Copy the code

Array to redo the classical four schemes:

  • Use the Set scheme of ES6

  • Compare the former term with each subsequent term

  • Use empty container storage to verify that it has been saved

  • Adjacent term scheme

The sort method is used to sort and does not generate a new array

Sorting algorithm
  • Bubble sort
    • Compare the current item with the next item, and put the largest item at the end of each round of comparison
    • The next round only compares the top part, not the biggest one that’s already at the end
let ary = [12, 23, 12, 15, 25, 23, 25, 14, 16]; function bubble(ary){ for(let i = 0; i < ary.length - 1; I++){for(let j = 0; j < ary.length-1-i; J++) {/ / in a layer which numerical control loop to the if (ary [j] > ary [j + 1]) {[ary [j], ary [m + 1]] = [ary [j + 1], ary [j]] / / ES6 deconstruction assignment}}}}Copy the code
  • Insertion sort
    • It’s like playing cards. If your new card is bigger than one of your cards, you put it behind this one, and you put it in front of you.
    • Take the first value and place it in a new array, then start with the second value and compare it from the largest to the smallest in the new array. If the value is larger than the value in the new array, place it after it. If the value is larger than the value in the first array, insert it at the front of the new array
let ary = [12, 23, 12, 15, 25, 23, 25, 14, 16]; function insert(ary){ let handle = []; handle.push(ary[0]) for(let i = 1; i<ary.length; i++){ let A = ary[i] for(let j = handle.length-1; j>=0; j--){ let B = handle[j] if(A>B){ handle.slice(j,0,A); // break A into B; } if(j===0){ handle.unshift(A); // If the first value is not greater than the first value, place it directly at the top of the array}}}}Copy the code

The unshift method inserts an element in the head of an array and does not generate a new array

  • Quick sort
    • Take out the middle items, put the items smaller than the middle items on the left, put the items larger than the middle items on the right, and do not process any more
let ary = [12, 23, 12, 15, 25, 23, 25, 14, 16]; Function quick(ary){if(ary. Length <= 1){return ary} let middleIndex = math.floor (ary. Length /2 MiddleValue = ary.splice(middleIndex,1)[0] let aryLeft = []; let aryRight = []; for(let i = 0; i < ary.length; i++){ ary[i]>middleValue? Aryright.push (ary[I]):aryLeft.push(ary[I])} // The recursive method keeps the left and right sides doing this until the left and right sides are aligned. Return quick(aryLeft). Concat (middleValue,quick(aryRight))}Copy the code
Array flattening
  • ES6: Flat method
let arr = [ [1, 2, 2], [3, 4, 5, 5], [6, 7, 8, 9, [11, 12, [12, 13, [14]]]], 10 ]; Arr = arr.flat(Infinity) // The parameters passed in are flat series; Infinity means flat infinite levelsCopy the code
  • toString
let arr = [ [1, 2, 2], [3, 4, 5, 5], [6, 7, 8, 9, [11, 12, [12, 13, [14]]]], 10 ]; Split (',').map((item)=>{return parseFloat(item)}) // after toString "1,2,2,3,4,5,5,6,7,8,9,11,12,12,13,14,10" / / split (', ') after [" 1 ", "2", "2", "3", "4", "5", "5", "6", "7", "eight" and "9", "11", "12", "12", "13", "14", "10"] // Then convert each term into a numberCopy the code
let arr = [ [1, 2, 2], [3, 4, 5, 5], [6, 7, 8, 9, [11, 12, [12, 13, [14]]]], 10 ]; arr = JSON.stringify(arr).replace(/\[|\]/g,'').split(', ').map((item)=>{return parseFloat(item)}) // json.stringify (arr) after ,4,5,5,2,2 "[[1], [3], [6,7,8,9, [11, 12, [12, 13, [14]]]], 10]"Copy the code
let arr = [ [1, 2, 2], [3, 4, 5, 5], [6, 7, 8, 9, [11, 12, [12, 13, [14]]]], 10 ]; arr.join('|').split(/(? :,|\|)/g).map((item)=>{ return parseFloat(item) })Copy the code
  • Loop validation array
    • Loop to check if it is an array, if it is, continue loop, if it is not, store directly
let arr = [ [1, 2, 2], [3, 4, 5, 5], [6, 7, 8, 9, [11, 12, [12, 13, [14]]]], 10 ]; Function flatten(arr){//some returns true for each item in the loop array. while(arr.some(item => Array.isArray(item))){ arr = flatten([].concat(... arr)) //[].concat(... Arr) doing so expands a layer. Recursion continues flattening} return arr; }Copy the code
some

Some verifies that any item in the array matches the rule. Some returns either true or false

Some checks if there are any elements in the array that match the criteria, and executes each element of the array in turn

  • If one of the elements meets the criteria, true is returned, and the remaining elements are not tested
  • If no condition is met, return false

Every is used to check whether all the elements in the array meet the criteria

  • If one of the checked arrays does not meet the criteria, return false and the rest are not checked
  • Return true if all conditions are met
var A = [3, 4, 5, 5] var B = A.some((item)=>{ return item >=5; // as long as the array is greater than 5 then B is true})Copy the code
find

Find returns the result if it exists, or undefined if it does not. And I’m only looking for the oh term

var A = [3, 4, 5, 5] var B = A.find((item)=>{ return item >=4; // undefined is not returned})Copy the code
Function (){function myFlat(){let result = [], _this = this; function(){let result = [], _this = this; let fn = (arr) => { for(let i = 0; i<arr.length; I ++){let item = arr[I] if(array.isarray (item)){// if(array.isarray (item)){ continue; } result.push(item) } } fn(_this) return result; } Array.prototype.myFlat = myFlat; })() arr = arr.myFlat();Copy the code
Fibonacci numbers

  • Method 1: recursion
// construct the first two items and check whether n starts with the third item (value 2). Function fabonacci(n){if(n<=1) return 1; // let arr = [1,1]; return fabonacci(n-2)+fabonacci(n-1) }Copy the code
  • Method 2:
function fabonacci(n){ if(n<=1) return 1; // let arr = [1,1]; let i = n +1 - 2; While (I >0){arr.push(arr[arr.leng-1]+arr[arr.leng-2]); } return arr[arr.length-1] }Copy the code
  • Method three: recursion
function fabonacci(count){ fn(count,curr=1,next=1){ if(count=0){ return 1; }else{return fn(count-1,next,curr+next)} return fn(count); }Copy the code
Bytedance classical algorithm problem
  • Input a positive number N, output all consecutive sequences of positive numbers that sum to N
  • For example, enter 15
  • Results: the [[1, 2, 3, 4, 5], [4 and 6], [7, 8]]
Function fn(count){let result = []; function fn(count){let result = []; let middle = Math.ceil(count/2) for(let i = 1; i<=middle; i++){ for(let j = 2;; J ++){if(total>count){break; if(total>count){break; if(total>count){break; }else if(total === count){ result.push(createArr(i,j)) break; } } } return result; } function createArr(n,len){ let arr = new Array(len).fill(null); arr[0] = n; arr = arr.map((item,index)=>{ return n+index }) return arr; }Copy the code

5.8

1. What is the difference between Call and apply? Which one has better performance?

Call and apply are both methods on the function prototype used to change what this refers to. The only difference is that the forms of the parameters passed in are different. Call passes parameters one by one, while Apply passes all parameters in array form. Bind is similar in that it changes the “this” pointer, but handles the function up front, but does not execute it immediately. In tests, Call performed slightly better than Apply.

// use the apply scenario let arr = [10,20,30], obj = {}; Function fn(x,y,z){} fn. Apply (obj,arr); Arr) // Based on the ES6 expansion operator, the expansion can be passed to the function in turnCopy the code

Do your own performance testing (for your information only, any code testing is dependent on the test environment. The current performance of cpus, memory, and Gpus does not have the same duration. Console. time Indicates the execution time of a program. The Firebug plugin can be installed in the Firefox browser for more accurate monitoring of the time

Console. time('A') //A name for(let I = 0; i<100000; i++){ } console.timeEnd('A')Copy the code

2. Write a re to verify this rule: A string of 6 to 16 characters must contain both uppercase and lowercase letters and digits

  • Forward lookup: The string to be matched must meet the pattern condition
  • Negative pre-check: The string to be matched must not meet the pattern condition
  • The content in parentheses is only the participation condition, not the actual condition
let reg = /^(? ! ^[a-zA-Z]+$)(? ! ^[A-Z0-9]+$)(? ! ^[0-9a-z]+$)(? ! [0-9] + $) [a zA - Z0-9] 6 16th} {$/Copy the code

$attr(name, value); $attr(name, value)

  • Equivalent to writing a property selector.
    • Get all tags, loop all tags. Get each tag, whatever attribute is passed in to get the attribute value. In special cases, the class stuff just needs to contain the value of this property
let ary = $attr('id','AAA') function $attr(property,value){ let elements = document.getElementByTagName('*'), Arr = []; Foreach. call(elements,item=>{}) // Elements = array. from(elements) elements. ForEach ((item)=>{let itemValue = Item.getattribute (property) // Get property if(property === 'class'){ New RegExp(/\b+value+\b/).test(itemValue)? Arr.push (item):null return; } if(itemValue === value){return arr. Push (item)}}) return arr; if(itemValue === value){return arr; }Copy the code

4. A string consisting of English letters and Chinese characters, using the re to add Spaces before and after English words

Let STR = "test, just test smileyqp", reg = /\b[a-z]+\b/ig; Replace (reg,value=>{//value =>{return ' '+value+' '}).trim(); //trim() removes leading and trailing Spaces; TrimLeft () removes leading space; TrimRight () to end space // STR "test a test, just test smileyqp"Copy the code

5, implementation,(5).add(3).minus(2)Make the output result 6

  • An instance of an object can call a method on the object’s circle. Since the number 5 can call add, add must be a method on the prototype number 5. The Number 5 belongs to the Number class, so the Number class must have an Add method
  • And since it is a chain call (chain writing), add must return a Number that can continue to call minus. Therefore, every time add returns a Number, that is, an instance of the Number class
(function(){ function check(n){ n = Number(n); Return isNaN(n)? } function add(n){n = check(n); Return this+n; } function minus(n){n = check(n);} function minus(n){n = check(n); return this-n; } //Number.prototype.add = add; //Number.prototype.minus = minus; ['add','minus']. ForEach ((item)=>{Number. Prototype [item] = eval(item); //eval converts string to expression})})() (5).add(3).minus(2)Copy the code

6. Differences between arrow functions and ordinary functions

  • Arrow functions are syntactically cleaner than normal functions (in ES6 each function can take a default parameter and use… Residual operator)
function fn(x){
  return function(y){
    return x+y
  }
}

let fn = x => y=>x+y
Copy the code
  • Arrow functions do not have this; this appears in the arrow function and belongs to its context (call, apply, etc., cannot change this reference).
let obj = {
  name:'smileyqp'
}
function fn1(){
  console.log(this)
}
fn1.call(obj)		//this =>  obj

let fn2 = ()=>{
  console.log(this)
}
fn2.call(obj)  //this  => window
Copy the code
  • There is no array of Arguments classes in the arrow function, only based on... argCollection of parameters passed (array)
let fn = (... Arg) = > {the console. The log (arg) / / [10, 20, 30]} fn (10, 30)Copy the code
  • Arrow functions cannot be executed by new because arrow functions have no this and no prototype
function Fn (){
  this.X = 100;
}
fn.prototype.getX = function(){}
let f = new Fn;
Copy the code

Question development:

Let arr = [10,20,30,'AA'], obj = {}; Arr = arr.each(function(item,index){// this => obj isNaN(item)){ return false; } return item*10; }, obj) // this method is [100,200,300,false]Copy the code
Replace, replace([REG re],callback) let STR = 'smileyqp2019smile2020' STR = str.replace(/smile/g,function(... Arg){// ArG stores information about each major and minor re matches. // Return the replaced string})Copy the code

5.10

7. Change the letters in the string from uppercase to lowercase and lowercase to uppercase

STR = str.replace(/ a-za-z /g,(content)=>{// The result of every re match // verify whether the re is capitalized: 1. Is it the same as the original after converting to uppercase? The original is uppercase. Whereas before find uppercase to lowercase, ASCII table 2 the values range (65-90) / / 1, the content. toUpperCase () = = = the content / / 2, content. charCodeAt () > = 65 | | content.charCodeAt <=90 return content.toUpperCase() === content? content.toLowerCase:content.toUpperCase; })Copy the code

8, implement string search

Implement a string matching algorithm that looks for the presence of string T in string S and returns the location of the first time if it exists, and -1 if it does not exist (not based on built-in methods such as indexOf and includes)

  • Loop s.length – t.length +1 times through each item in the original string. Compare each item with T from the current position block
(function(){function myIndexOf(T){// This original string, i.e. S let lenT = t. length, lenS = s.length, result = -1; if(lenT>lenTS){ return -1; } for(let i = 0; i<lenS-lenT+1; i++){ let substr = S.substr(i,lenT) if(substr === T){ result = i; break; } } return result; } String.prototype.myIndexOf = myIndexOf; })() let S = 'yqp27982348 smile&& smile', T = 'smile' console.log(s.myindexof (T))Copy the code
  • Idea 2: regular processing
    • The direct re matches this string, and returns -1 if the result is NULL. The null part can be found directly in the re match result index
(function(){function myIndexOf(T){//this primitive string, i.e. S let reg = new RegExp(T), res = reg.exect(this); return res === null ? -1:res .index } String.prototype.myIndexOf = myIndexOf; })() let S = 'yqp27982348 smile&& smile', T = 'smile' console.log(s.myindexof (T))Copy the code

9, verify that the input is a correct url

1. Agreement HTTP, HTTPS FTP. 2, the domain name www.smileyqp.com smileyp cn smile.yqp.smileyqp.com.cn 3, request path index. The HTML/stu. Stu/index. The HTML 4, question marks the refs ? Name = 18 smileyqp&age = 5, hash value agreement, request path, passing on the question mark and hash can be omitted the let STR = 'http://www.smileyqp.com/index.html' legs reg = /^((http|https|ftp):\/\/)?(([\w-]+\.) +[a-z0-9]+)((\/[^/]*)+)? (? : \? [^ #] +)? (#. +)? $/i;Copy the code

5.11

10. Prototype chain

function Foo(){ Foo.a = function(){ console.log(1) } this.a = function(){ console.log(2) } } Foo.prototype.a = function(){ console.log(3) } Foo.a = function(){ cosnole.log(4) } Foo.a(); //4 let obj = new Foo(); // New Foo() also executes Foo as a function; A =>1 obj =>2 obj.a(); //2 Foo.a(); / / 1Copy the code

11. Lazy loading of images

  • An important solution of front-end performance optimization, through the lazy loading of images or data, can accelerate the page loading speed, the first loading speed is faster, and only slide to the image part will be loaded
  • Treatment scheme
    • Put all images that need lazy loading in a box, set the width and height and default placeholder
    • Start with empty SRC for all images, place the image’s real address on the image’s custom property, and hide img
    • We wait until all other resources have loaded before loading the image
    • For many images, load the image after the current image is fully displayed as the page scrolls

  • Single picture lazy loading
//html <! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta < span style> *{margin: 0; max-width: 100%; padding: 0; } .imgBox{ margin: 1000px auto; width: 300px; height: 200px; overflow: hidden; background: pink; } .imgBox img{ width: 100%; } < / style > < / head > < body > < div class = "imgBox" > < img SRC = "" Alt =" lazy loading" data-img="https://gss0.baidu.com/9vo3dSag_xI4khGko9WTAnF6hhy/zhidao/pic/item/3ac79f3df8dcd100bbd10c8e738b4710b8122fcb.jp g"/> </div> <script src="node_modules/jquery/dist/jquery.min.js"></script> <script src="./delayImg.js"></script> </body>  </html>Copy the code
ImgBox = $(".imgbox "), $img = $imgbox. children('img'), $window = $(window) /** * */ / $(document).ready(); */ / $(document).ready(); // The dom structure is loaded$(window).on('load scroll'.function(){// Both load and scroll events are triggered; Event binding in JQuery supports multi-event binding. When two events are triggered, the same event is executed.if($img.attr('isLoad')==='true'){ return; } console.log('ok') let $A = $imgbox.outerheight () + $imgbox.offset ().top; Let $B = $window. OuterHeight () + $window. The scrollTop () if (A < = $B) {/ / load the real picture $img. The attr (' SRC '$img. Attr (' data - img)) $img. On (' load '() = > {/ / success/loading / $img. CSS (' display', 'block') console. The log (' images load success! ') $img.stop().fadein () //fadeIn is a fadeIn jq}) $img.attr('isLoad',true)Copy the code

  • Lazy loading of multiple images
//html <! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta < span style> *{margin: 0; max-width: 100%; padding: 0; } .container{ width: 800px; margin: 0 auto; } .imgBox{ margin: 0px auto; width: 300px; height: 200px; overflow: hidden; background: pink; margin-bottom: 20px; } .imgBox img{ width: 100%; </style> </head> <body> <div class="imgBox"> <div class="imgBox"> data-img="https://gss0.baidu.com/9vo3dSag_xI4khGko9WTAnF6hhy/zhidao/pic/item/3ac79f3df8dcd100bbd10c8e738b4710b8122fcb.jp g"/> </div> </div> <script src="node_modules/jquery/dist/jquery.min.js"></script> <script src="./moredelayImg.js"></script> </body> </html>Copy the code
//moredelayImg.js let $container = $('.container'), str = ``, $imgBoxs = null, $window = $(window) new Array(20).fill().foreach ((item)=>{//new Array(20).fill() creates an Array of length 20 and fills STR +='<div with null forEach entry ImgBox ><img SRC ="" Alt ="" data-img="https://gss0.baidu.com/9vo3dSag_xI4khGko9WTAnF6hhy/zhidao/pic/item/3ac79f3df8dcd100bbd10c8e738b4710b8122fcb.jp g"/></div>' }) console.log(str)$container.html(str);
$imgBoxs = $container.children('.imgBox');// Multiple images are loaded lazily$window.on('load scroll', () = > {Let $B = $window.outerheight () + $window.scrolltop () console.log($imgBoxs) $imgboxs. each((index,item)=>{console.log(index,item) let $item = $(item), $itemA = $item.outerHeight() + $item.offset().top, isLoad = $item.attr('isLoad') if($itemA <= $B && isLoad ! $item.attr('isLoad',true); $img = $item. Children (' img) $img. Attr (' SRC '$img. Attr (' data - img) $img) on (' load' () = > {/ / loading / / success $img. CSS ('display','block') console.log(' Image loaded successfully! ') $img.stop().fadein () //fadeIn is an asymptote in jq})}}); })Copy the code

12. Array intersection

Let nums1 = [1,2,3,2] let nums2 = [2,2,2] let arr = []; for(let i = 0; i<nums1.length; i++){ let item1 = nums1[i] for(let j=0; j<nums2.length; j++){ let item2 = nums2[j] if(item1===item2){ nums1[i] = null; nums2[j] = null; arr.push(item1) break; }}} console.log(arr) //[2,2]Copy the code
Let nums1 = [1,2,3,2] let nums2 = [2,2,2] let arr = []; nums1.forEach((item,index)=>{ let n = nums.indexOf();	if(n>0) {
    nums1.splice(index,1)
    nums2.splice(n,1)
    arr.push(item)
	}
})
Copy the code

Rotate the array

Given an array, move the elements of the array k positions to the right, where k is non-negative, for example:

Input: [1,2,3,4,5,6] and k=3

Output:,6,1,2,3,4 [5]

  • slice
Input: [1,-100,78,90] k = 2 [,78, 1, 90-100] function rotate (key) {/ / processing parameters, key > 0 if (key < 0 | | key = = = 0 | | key = = = this. Length) return this.  if(key>this.length){key = key%this.length}// Slice supports negative indexes, Return this.slice(-key).concat(this.slice(0,this.length-key))} array.prototype. rotate = rotate; Let arr = [1,2,3,4,5,6,7], k = 3; arr.rotate(3); // [5, 6, 7, 1, 2, 3, 4]Copy the code

Slice parameters: start point, end point, return: cut array

Splice parameters: start point, length, return: The deleted part is returned

  • splice
Input: [1,-100,78,90] k = 2 [,78, 1, 90-100] function rotate (key) {/ / processing parameters, key > 0 if (key < 0 | | key = = = 0 | | key = = = this. Length) return this.  if(key>this.length){key = key%this.length}
  
   return this.splice(this.length-key,key).concat(this)
}
Array.prototype.rotate = rotate;



let arr = [1,2,3,4,5,6,7],
		k = 3;
arr.rotate(3);		// [5, 6, 7, 1, 2, 3, 4]
Copy the code
  • Delete the last item and put it at the top, k times
Input: [1,-100,78,90] k = 2 The function the rotate (key) {/ / processing parameters, key > 0 if (key < 0 | | key = = = 0 | | key = = = this. Length) return this;  if(key>this.length){key = key%this.length}for(let i = 0; i<=key; i++){ this.unshift(this.pop()); //this.pop() the last item; } return this; } Array.prototype.rotate = rotate; / / write 2: the function the rotate (key) {/ / processing parameters, key > 0 if (key < 0 | | key = = = 0 | | key = = = this. Length) return this;  if(key>this.length){key = key%this.length}new Array(k).fill('').forEach((item)=>{ this.unshift(this.pop()); //this.pop() the last item; }) return this; } Array.prototype.rotate = rotate; Let arr = [1,2,3,4,5,6,7], k = 3; arr.rotate(3); // [5, 6, 7, 1, 2, 3, 4]Copy the code

5.12

14. The idea of coriation of functions

  • Function corrification: The idea of pre-processing (using the mechanism of closures)
let obj = { name:'OBJ' } function fn(... arg){ console.log(this,arg) } document.body.onclick = fn; //this=>BODY document.body.onclick = function(ev){//this=>BODY document.body.onclick = function(ev){//this=>BODY document.body.onclick = function(ev){//this=>BODY document.body.onclick = function(ev){//this=>BODY document.body.Copy the code

Implementation:

  • When clicked, the this pointer is changed to obj and the event object is passed along with two parameters 100,200
Function (){//bind is a classic currie (function(){//context is passed to obj to change the reference to this, if not the default is to say window function myBind(context=window,... outerArgs){ let _this = this; return function(... innerArgs){ _this.call(context,... innerArgs.concat(outerArgs)) } } Function.prototype.myBind = myBind; })() let obj = {name:' obj '} document.body.onclick = fn.mybind (obj,100,200)Copy the code

Function corridorization: takes advantage of the idea of closure preservation, that is, function execution forms a closure that stores variable values and uses them when needed

  • Closures do two things:

    • To protect the
    • save
  • The simplest example of coiling function programming ideas. Corrification = closure. Form a closure with parameters for the subset to use.

Return function(y){return x+y}} fn(100)(200); However, the closure value is preserved for the second method executionCopy the code
  • A classic case

Please add an add function to achieve the following functions: (1) add / / 1 (1) (2) / / 3 add (1) (2) (3) / / 6 add (1) (2) (3) (4) / / add 10 (1) (2, 3) / / 6 add (1, 2) (3) / / 6 Add (1, 2, 3) / / 6

Function currying (fn, length) {/ / function length is obtained it how many parameter length = length | | fn. Length; return function(... args){ if(args.length >= length){ return fn(... args) } return curring(fn.bind(null,... args),length-args.length) } } let add = currying((... Args)=>{return eval(args. Join ('+'))},5); This is no matter how many times the function is called, just the number of argumentsCopy the code

  • add(1)(2)(3)(4)Step analysis

  • Add (1, 2) (3, 4)Step analysis

15. Write new by hand

function Dog(name){ this.name = name; } Dog.prototype.bark = function(){ console.log('bark') } Dog.prototype.sayName = function(){ console.log('my name Is '+this.name)} to implement a _new method implement the following: let dog = _new(dog,'dooooog') dog.sayname () dog.bark()Copy the code

1. Form a private scope as normal function execution

  • Parameter value
  • Variable ascension

By default, an object is created, but this in the function refers to this object, which is the current instance

function _new(Fn,... Arg){//Fn is the current class to be new; //let obj = {}; //Fn.call(obj,... arg) let obj = Object.create(Fn.prototype); Prototype obj.__proto__ = Fn. Prototype; return obj; }Copy the code

Note: Object.create creates an empty Object and the prototype chain of the Object points to the parameter we passed.

Array merge

  • Question 1:

let ary1 = ['A1','A2','B1','B2','C1','C2','D1','D2'] let ary2 = ['A','B','C','D'] Arr.sort ((a,b)=> a.localecompare (b))); Ary2 = ary2.map(item=>item+'Z') let arr = ary1.concat(ary2) Arr. Sort ((a, b) = > a. ocaleCompare (b)). The map (item = > {return item. Replace (' Z ', ') / / remove Z}) console. The log (arr) / / [" A1 ", the "A2", "A", "B1", "B2", "B", "C1", "C2", "C", "D1", "D2", "D"]Copy the code
  • Topic 2:
The let ary1 = [' D1, D2, A1, A2, C1, C2, B1, B2 ' '] let ary2 = [' B ', 'A', 'D', 'C'] / / requirement for combined output array of [" D1 ", "D2", "D", "A1", "A2", "A","C1", "C2", "C","B1", "B2", "B"] let n = 0; for(let i = 0; i<ary2.length; i++){ let item2 = ary2[i] for(let j = 0; j<ary1.length; j++){ let item1 = ary1[j] if(item1.includes(item2)){ n = j; // Contains the record index, which is updated by an include. Ary1. splice(n+1,0,item2) // Delete 0 items from n+1, insert item2 before n+1, Also is equivalent to n behind the n + 1} the console. The log (ary1) / / [" D1 ", "D2", "D", "A1", "A2", "A", "C1", "C2", "C", "B1" and "B2", "B"]Copy the code

17, closures

for(var i = 0; i<10; I ++){setTimeut(()=>{console.log(I)},10000)} SetTimeout is asynchronousCopy the code
For (let I = 0; let I = 0; i<10; I++) {setTimeut (() = > {the console. The log (I)}, 10000)} / / 0,1,2,3,... Because it is not a private variable. SetTimeout is asynchronousCopy the code
I for(var I = 0; i<10; i++){ (function(i){ setTimeut(()=>{ console.log(i) },10000) })(i) }Copy the code
// For (var I = 0; i<10; i++){ setTimeut(((i)=>{ return ()=>{ console.log(i) } })(i),10000) }Copy the code
// You can also use bind to hold the value of I, based on the bind pre-processing mechanism. Var fn = function(I){console.log(I)} for(var I = 0; i<10; i++){ setTimeut(fn.bind(null,i),10000) }Copy the code

18. Anonymous functions

  • Anonymous functions with a function name cannot be called outside the function, but can be called inside the function
  • This name is a constant, and the value stored by this name cannot be changed (non-strict mode does not generate an error, but does not have any effect, strict mode directly generates an error. Constants created by const)
Let fn = unction AAA(){console.log(AAA)}Copy the code
var b = 10; (function b(){ b = 20 console.log(b) //function b; })() console.log(10) //10Copy the code
var b = 10; Function (){function(){function(){function(){function(){function(){function(){function(){function(){function(){function()Copy the code

Now, how to change the value of b in the above anonymous function log to 20, and the global b is still 10?

  • Make b private, declare it, or change it to a parameter
Var b = 10; (function b(b){// form parameter b = 20 console.log(b) //20})() console.log(10) //10 // (function b(){let b = 20 console.log(b) //20})() console.log(10) //10Copy the code

18,var a = ?makea==1&&a==2&&a==3

# # # # # = = and = = =

  • = =Compare, if the left and right data types are not the same then convert to the same data type and then compare
    • = = {} {}The address of heap memory is compared when two objects are compared
    • null==undefined Equal, but three equal signs are not equal
    • NaN == NaNNo, NaN is not equal to anyone
    • [12] = = "12"Object and string items are compared after the object toString is converted to a string
    • All other cases are converted to numbers for comparison (toString is converted toString, then converted to number) (if the type is different)
      • Objects to numbers are converted to strings and then converted to numbers
      • Strings are converted to numbers, and whenever a non-numeric character occurs, the result is NaN
      • Boolean to digits: true => 1 false=>0
      • nullConvert to the number 0
      • undefinedConvert to the number NaN
[12] = = true are converted into digital. = > Number ([12]. ToString () output 12 = = 1 is not equal to [] [] = > 0 = = false false = > 0 is equal to [] [] = = 1 = > 0 is not equal to "1" = = 1 Equal true == 2 not equalCopy the code
var a = ?makea==1&&a==2&&a==3

Add a private toString method to the object and refactor the private method

  • Method one:
Var a= {n:0, toString:function(){// If a==1&&a==2&&a==3 Return ++ this.n; }}Copy the code
  • Method 2
Var a= [1,2,3] a.tostring = A.hift A ==1&&a==2&&a==3Copy the code
  • Methods three
let n = 0; Object.defineProperty(window,'a',{ get:function(){ return ++n; DefineProperty (window,'a',{get:function(){this.val? This.val ++:this.val=1; }})Copy the code

New method in ES6

  • Array

    • From converts the rest to an array
    • IsArray Checks whether the array is an array
  • String.fromCharCode(122) => z. 'z'.charCodeAt() => 122

  • Object.create([obj]) creates an empty Object that the prototype chain points to

  • Object.defineproperty Is used to define parameters in an Object. Three parameters: Object, attribute, and value

DefineProperty (obj,'name','smileyqp') lets obj = {name:'Jane'} // object.defineProperty (obj,'name','smileyqp') DefineProperty (obj,'name',{get:function(){return 'smileyqp'}, set:function(){ return 'Mary' } })Copy the code

5.13

The object calls the push method

let obj = { 2:3, 3:4, length:2, Push: Array. Prototype. Push} obj. Push (1) / / = > obj/obj. Length = 1 = > obj [2] = 1 length based on the original plus one obj/length = > 3 obj. Push (2) ////= "obj[obj. Length]=2 => obj[3]=2 console.log(obj) // Length: 4, push: Array. Prototype. Push} / / Array principle Array. The push method prototype. Push = function (val) {this [. This length] = val; return this.length; // Push an element to the end of the array to return the length of the arrayCopy the code

Object to array

Let obj = {1:2323, 4:3492, 8:2673} get [2323, NULL, NULL, 3492, NULL, null, 2673, null, null, null, null, null, null]

  • New Array().fill(null) and map with index
let obj = { 1:2323, 4:3492, 8:2673 } let arr = new Array(12).fill(null).map((item,index)=>{ return obj[index+1]? obj[index+1]:item })Copy the code
  • Method 2: use obj. Length, then array. from
Let obj = {1:2323, 4:3492, 8:2673} obj. Length = 13 //Array. undefined, 3492, undefined, undefined, undefined, 2673, undefined, undefined, Array.from(obj).slice(1).map(item=>{return item:null})Copy the code
  • 3. Use object.keys
Let obj = {1:2323, 4:3492, 8:2673} // object.keys, Let arr = new Array(12).fill(null) object.keys (obj).foreach (item=>{arr[parseInt(item)-1] = obj[item] })Copy the code
Basic array-related methods

21. Value Types & Reference Types (Variable types)

Deep copy

  • Value types
let a = 100;
let b = 1;
a = 200;
console.log(b) //100
Copy the code
  • Reference types
let a = {age:10};
let b = a;
b.age = 20;
console.log(a.age)	//20
Copy the code
  • Common value types

    • undefined
    • string
    • number
    • boolean
    • symbol
  • Common reference types

  • obj

  • array

  • Null Special reference type pointing to an empty address

  • Function A special reference type that does not store data, so there is no ‘copy, assign’

const obj1 = {x:100,y:200} const obj2 =obj1; let x1 = obj1.x; Obj2. x = 101; x1 = 102; console.log(obj1) //{x:101,y:200}Copy the code

Typeof operators (variable types) and deep copies

  • Determine all value types
  • Check whether function
  • Determine whether to reference a type (cannot be subdivided)

Deep copy
function deepClone(obj = {}){ if(typeof obj ! == 'object'||obj === null){ return obj; } // initialize the result let result; if(obj.instanceof Array){ result = [] }else{ result = {} } for(let key in obj){ if(obj.hasOwnProperty(key)){ Result [key] = deepClone(obj[key])}} return result; }Copy the code

23. Variable calculation and type conversion

  • String splicing
const a = 100+10;		//110
const b = 100+'10';	//10010
const c = true+'10';	//true10
Copy the code
  • = =
100 = = '100'; //true 0 == ''; //true 0 == false; //true false ==''; //true null == undefined; //trueCopy the code

Use === for everything except ==null. And, for example: a = = null is equivalent to a = = = undefined | | = = = null

  • If statement and logical operations (If statement determines Truely variables and Values variables)
    • Truely variable and Services variable
      • Truely variable: A two-step non-operation yields true.!!!!! a===true
      • Services variable: two steps non-computation gives false.!!!!! a===false

  • Logical judgment (also Truely variable and Service variable)

5.14

Class and inheritance

class Student{
  constructor(name,age){
    this.name = name;
    this.age = age;
  }
  sayHi(){
    console.log('hi'+this.name+this.age)
  }
}

let stu = new Student('smileyqp',100)
Copy the code
inheritance
  • extends
  • super
  • Extend or override methods
class Person(){ constructor(name,age){ this.name = name; this.age = age; } eat(){ console.log(this.name+'eat food') } } class Student extends Person{ constructor(name,age,number){ super(name,age) this.number = number; } class Teacher extends Person{constructor(name,age,major){console.log('hi'+this.name+this.age)}} Class Teacher extends Person{constructor(name,age,major){ super(name,age) this.major = major; } teach(){console.log(this.name+'teach'+this.major)}} let smileyqp = new Student('smileyqp',20) // add smileyqp.eat() Smileyqp eat food smileyqp.__proto__ () smileyqp eat food smileyqp.__proto__ (Copy the code
instanceof
  • Instanceof determines the type of reference
  • Object is the parent of all classes
smileyqp instanceof Student;	//true
smileyqp instanceof Person;	//true
smileyqp instanceof Object;	//true

[] instanceof Array;	//true
{} instanceof Object;		//true
[] instanceof Object;		//true
Copy the code

25. Prototype and prototype chain

  • Each class has a display prototypeprototype
  • Each instance has an implicit stereotype__proto__
  • An implicit stereotype of an instance__proto__All point to the prototype of the corresponding classprototype
Console. log(smileyqp.__proto__) // Console. log(student.prototype) // Explicit prototype console.log(smileyqp.__proto__ === Student.prototype) //trueCopy the code
Get instance properties or methods (prototype-based execution rules)
  • Start by looking up its own properties and methods
  • If you can’t find it, get there__proto__Look for
Prototype chain

console.log(Student.prototype.__proto__)
console.log(Person.prototype)	
console.log(Student.prototype.__proto__ === Person.prototype)
Copy the code
instanceof
  • Tracing the prototype chain returns true if it does, false if it does not
Prototype prototype chain related questions
  • How to determine if a variable is an Array (type: instanceof, an instanceof Array)
  • Write a proposed jQuery, consider plug-ins and extensibility (prototypes and prototype chains)
/ / jquery do dom query class jquery {constructor (selector) {cons result = documnent. QuerySelectorAll (selector) const length = result.length; for(let i = 0; i < length; i++){ this[i] = result[i] } this.length = length; this.selector = selector; } get(index){ return this[index] } each(fn){ for(let i =0; i<this.length; i++){ const elem = this[i]; fn(elem) } } on(type,fn){ return this.each(elem=>{ elem.addEventListener(type,fn,false) }) } } const $p = new jQuery('p')$p.get(1)
$p.each(elem=>console.log(elem.nodeName))
$p.on('click',()=>{alert('click')})


Copy the code
//2, class mymy.extends jQuery{// 3, class mymy.extends jQuery{// 3, class mymy.extends jQuery{// 3, class mymy.extends jQuery{ Constructor (selector){super(selector)} // Extend your method addClass(className){} style(data){}}Copy the code
  • How to understand the prototypical nature of a class (class and inheritance)
    • Diagrams of prototypes and prototype chains
    • Execution rules for properties and methods

Scope and closure

  • How to value this in different application scenarios
  • Handwritten bind
  • The application scenarios of closures in actual development are illustrated with examples
// Create 10 <a/> tags, click to pop up the corresponding serial number let I,a; for(i = 0; i<=10; i++){ a = document.createElement('a'); a.innerHTML = i+"<br/>"; a.addEventListener('click',function(e){ e.preventDefault(); alert(i) //10 }) document.body.appendChild(a) } let a; for(let i = 0; i<=10; I ++){//let I define block scope a = document.createElement('a'); a.innerHTML = i+"<br/>"; a.addEventListener('click',function(e){ e.preventDefault(); Alert (I) / / 1, 2, 3, 4, 5... }) document.body.appendChild(a) }Copy the code
Scope and free variables
  • Scope: The legal scope of a variable

  • Scope classification

    • Global scope
    • Function scope
    • Block-level scopes (new in ES6)
    If (true){let x = 100; } console.log(x);} console.log(x);} console.log(x);} console.log(x); / / complainsCopy the code

Free variables
  • Free variable: A variable that is not defined in the current scope but is used
  • Search through the parent scope, layer by layer, until you find it
  • An error is reported if the global scope is not foundxx is undefined
closure
Function create(){let a = 100; return function(){ console.log(a) } } let fn = create(); let a = 200; fn(); // function 100 is executed in global scope; The definition of the function is in the create function, looking up in the upper scopeCopy the code
Function print(fn){let a = 200; fn() } let a = 100; function fn(){ console.log(a) } print(fn); / / 100Copy the code
  • Closure: The lookup of a free variable is done where the function is defined, to the parent scope, not to the execution

27, this

  • As a general function
  • Use call, bind, apply
  • Called as an object method
  • Called in the class method
  • Arrow function
What does this take: the value is determined at the time the function is executed, not at the time the function is defined
function fn1(){
  console.log(this)
}
fn1();	//window

fn1.call({x:100})		//{x:100}

const fn2 = fn1.bind({x:200})
fn2();	//{x:200}
Copy the code

Arrow functions do not have this, where this takes the parent scope this

//demo1 const zhansan = {name:'zhangsan', sayHi(){console.log(this) //this current object}, wait(){ setTimeout(function(){ console.log(this) //this window }) } } //demo1 const zhangsan = { name:'zhangsan', SayHi (){console.log(this) // Current object}, waitAgain(){setTimeout(()=>{console.log(this) // Current object})}}Copy the code
Handwritten bind
Function. The prototype. Mybind = function () {/ / an Array parameter apart for const args = Array. The prototype. Slice. The call (the arguments); Const t = args.shift(); // bind fn1 const self = this; return function(){ return self.apply(self,args) } }Copy the code
Application of closures
  • Hidden data
  • Make a simple cache tool
Function createCache(){const data = {} return {set:function(key,val){data[key] = val; }, get:(){return data[key]}}} // hide from external access, means that c can only be obtained by set, get. C = createCache() const c = createCache(); c.set('a',100); c.get('a');Copy the code

5.16

28. Synchronous and asynchronous

// Async console.log(1) setTimeout(()=>{console.log(2)},1000) console.log(3) // Async console.log(1) alert(2) console.log(3)Copy the code
  • What is the difference between synchronous and asynchronous
    • Js based is a single threaded language
    • Asynchrony does not block code execution
    • Synchronization blocks code execution
  • Handwritten Promise loads an image
const src = '.. /xxximg.png' function loadImg(){ return new Promise((resolve,reject)=>{ let img = document.createElement('img') Img. onload = function(){console.log('loaded') resolve(img)} mg.onrror = function(){reject(new Error('load failed ${SRC} ')) } img.src = src }) } loadImg().then(img=>{ console.log(img) return img }).catch(err){ console.log(err) }Copy the code
  • What are the asynchronous scenarios used by the front end

    • Web requests, such as Ajax image loading

      onsole.log('start')
      let img = document.createElement('img')
      img.onload = function(){
        onsole.log('loaded')
      }
      img.src = './xxx.png'
      console.log('end')
      Copy the code
    • A scheduled task, such as setTimeout

knowledge
  • Single-threaded vs. asynchronous (asynchrony comes from the single-threaded background)

    • JS is a single-threaded language that can only do one thing at a time

    • Browsers and NodeJS already support Js startup processes such as Web workers. But that doesn’t change the fact that JS is single threaded

    • Js and DOM rendering share the same thread because Js can modify the DOM structure

    • Cannot be stuck when waiting (network request, scheduled task)

    • Asynchrony is needed to solve the single thread problem

    • Callback function form

review

Knowledge module
  • Variable types and calculations
  • Prototype and prototype chain
  • Scope and closure
  • Asynchronous and single threaded
The title
  • Typeof determines which types

    • The base type
    • Reference types
  • When to use === when to use ==

  • The difference between value types and reference types

  • Handwritten deep copy

knowledge
  • Value type vs reference type, stack model, deep copy
  • What does the Typeof operator do
  • Type conversion, Truely and Services variable
The topic of prototype and prototype chain
  • How to determine if a variable is an array (instanceof prototype chain lookup)
  • Write a jquery by hand, consider plug-ins and extensibility
  • How to understand the prototypical nature of class
Prototype and prototype chain knowledge points
  • Class and inheritance, combined with handwritten jquery example understanding
  • Instanceof appearance and essence
  • Stereotypes and prototype chains: Schematics & enforcement rules
Closures and scopes
  • How to value different reference scenarios for this

    • This is defined at function execution time, not function definition time
  • Handwritten bind

  • Closure scenarios encountered in real development, with examples (eg: Hide data, provide API only)

1,2,3,4,5,6,7,8,9,10 let a; for(let i = 0; i<=10; i++){ a = document.createElement('a') a.innerHTML = i+'</br>'; a.addEventListener('click',function(e){ e.preventDefault() alert(i) }) document.body.appendChild(a) }Copy the code
Scope and closure knowledge
  • Scope and free variables (free variables are not defined in the current block scope, but are used here)
  • Closures: Two common forms & free variable lookup rules
  • this
Asynchronous and single threaded topics
  • The difference between asynchronous and synchronous
  • Handwritten Promise loads an image
  • The front-end uses asynchronous scenarios
    • An ajax request
    • setTimeout
Asynchronous and single threaded knowledge
  • The difference between single-threaded and asynchronous, asynchronous and synchronous
  • Front-end Asynchronous application Scenario (Network request & Scheduled Task)
  • Promise resolves the callback hell problem