当前位置:网站首页>[interview question bank] record (II)

[interview question bank] record (II)

2021-09-15 06:31:35 Infinite loop infinite

One 、com 1

xiang wang

1. Vue Responsive principle

answer :Vue2 yes Object.defineProperty And Observer mode .Vue3 yes proxy And Observer mode

image.png

1) Precautions for detecting changes

because JavaScript The limitation of ,Vue  Can 't detect Array and object changes

1.1) For the object

Vue Unable to detect property To add or remove . because Vue When initializing an instance property perform getter/setter conversion , therefore property Must be in  data  Objects exist to make Vue Convert it to responsive . for example :

var vm = new Vue({ data:{ a:1 } }) // `vm.a`  It's reactive  vm.b = 2 // `vm.b`  It's nonresponsive 
 Copy code 

For instances that have already been created ,Vue Dynamic addition of root level responsive property. however , have access to  Vue.set(object, propertyName, value)  Method to add a response to a nested object property. for example , about :

Vue.set(vm.someObject, 'b', 2)
 Copy code 

You can also use it  vm.$set  Example method , This is the whole picture  Vue.set  Method alias :

this.$set(this.someObject,'b',2)
 Copy code 
1.2) For arrays

Vue The following array changes cannot be detected :

  1. When you use the index to set an array item directly , for example :vm.items[indexOfItem] = newValue
  2. When you change the length of an array , for example :vm.items.length = newLength

for instance :

var vm = new Vue({
    data: {
        items: ['a', 'b', 'c'],
    },
});
vm.items[1] = 'x'; //  Not responsive 
vm.items.length = 2; //  Not responsive 
 Copy code 

To solve the first problem , Both of the following methods can realize and  vm.items[indexOfItem] = newValue  Same effect , At the same time, the status update will be triggered in the responsive system :

// Vue.set
Vue.set(vm.items, indexOfItem, newValue)
 Copy code 
// Array.prototype.splice
vm.items.splice(indexOfItem, 1, newValue)
 Copy code 

You can also use  vm.$set  Example method , This method is global  Vue.set  An alias for :

vm.$set(vm.items, indexOfItem, newValue)
 Copy code 

In order to solve the second kind of problems , You can use  splice

vm.items.splice(newLength)
 Copy code 

2. webpack loader Is there a sequence , Difference from plug-ins

answer : The function formula is used for reference The idea of function combination : - webpack Load from right to left

2.0 webpack loader And plugin The difference and implementation of loader And plug-ins

Loader It's actually a converter , Translate what you entered , Nothing has changed in essence , Just like translating Chinese into English

be relative to Loader Come on , Actually plugin The mechanism is more flexible , It can be webpack Change the output during the operation of . In a nutshell Add bricks and tiles to the output .

Realization Loader And plug-ins zhuanlan.zhihu.com/p/28245984

module:{
        rules:[{
            test:/\.js$/,
            use:[{
                loader:'babel-loader',
                options:{
                    presets:['react']
                }
            }]
        }]
    }
 Copy code 

2.1 url-loader

url-loader Introduce pictures , It can be said that it is file-loader Enhanced Edition

url-loader Will use our pictures base64 Encoded as another string , Web pages can recognize such coded things , The advantage of this is , It reduces requests for pictures , You just ask to go back to this page , The picture is coming , Can reduce network requests , But if the picture is too big , This string will become very large , Make the loaded file very large

So if the picture is small , There's no need to ask them to re request pictures , Write it directly into the page , Let the browser parse , When the picture is too large , Don't let him code , Look at the following implementation process

{
    test:/\.jpg|gif|png$/,
    use:[{
        loader:'url-loader',
        options:{
            limit:10000// With bit In units of , When less than 10000bit when , code , Greater than 10000bit when , No coding 
        }
    }]
}
 Copy code 

When using url-loader When dealing with some resources , All resources will be used by default base64 Code in the form of , But we can give it a limit Attribute to restrain him , When the resource is less than a certain value , To code , When not less than this value , In fact, it will hand over this resource to file-loader To deal with

3. Vuex install What has been done ( Source code )

answer :vue The only way to use plug-ins is Vue.use(plugin), about Vuex Namely Vue.use(Vuex) .

4. Strong cache negotiation cache

answer : priority : Strong cache > Negotiate the cache

Strong cache : Cache-Control > Expires(http1.0 product , Affected by local time )

Negotiate the cache : ETag File fingerprint comparison (http1.1 appear ) > Last-Modified Finally, modify the time comparison (Last-Modified When you open a file, it changes , In seconds )

5. Data of address component in e-commerce website 2M Too big , How to deal with it ,

answer : My personal advice : Batch request , On demand request . Data cache to localStorage

6. Detailed description CSRF Cross domain Request Forgery

answer :www.jianshu.com/p/7f33f9c79…

image.png

Defense in the industry right now CSRF There are three main strategies to attack :

  • verification HTTP Referer Field ;
  • Add... To the request address token And verify ;
  • stay HTTP Custom properties in the header and verify
Think about it
  • Attacker website B How to send requests across domains to the attacker A Website : adopt img Tag send request
  • Attackers can also capture packets https Package form , Grab A In the request header token Information , because tooken It can be used within the expiration time .

7. Vue Asynchronous update queue

answer : Vue Updating DOM When is asynchronous Executive . Just listen for data changes ,Vue A queue will be opened , And buffer all data changes that occur in the same event cycle . If the same watcher Triggered multiple times , Will only be pushed into the queue once . This de duplication of data in buffering avoids unnecessary computation and DOM Operation is very important . then , In the next event loop “tick” in ,Vue Refresh the queue and execute the actual ( It's gone heavy ) Work .Vue Try using native... Internally for asynchronous queues  Promise.thenMutationObserver  and  setImmediate, If the execution environment does not support , Will use  setTimeout(fn, 0)  Instead of .

To wait after the data changes Vue Update complete DOM, It can be used immediately after data changes  Vue.nextTick(callback). So the callback function will be in DOM Called after the update is complete

methods: {
    updateMessage: function () {
      this.message = ' Updated '
      console.log(this.$el.textContent) // => ' Not updated '
      this.$nextTick(function () {
        console.log(this.$el.textContent) // => ' Updated '
      })
    }
}

 Copy code 

because  $nextTick()  Return to one  Promise  object , So you can use the new  ES2017 async/await  Grammar does the same thing :

methods: {
    updateMessage: async function () {
      this.message = ' Updated '
      console.log(this.$el.textContent) // => ' Not updated '
      await this.$nextTick()
      console.log(this.$el.textContent) // => ' Updated '
    }
 }
 Copy code 

8. vue in Toast Package of plug-ins . such as toast How components are mounted to Vue Archetype ?

answer :

// Import components 
import Toast from './Toast'

const obj = {}

// install Method 
obj.install = function(Vue) {
    // 1. Create a component constructor 
    const toastConstructor = Vue.extend(Toast)

    // 2.new A component object 
    const toast = new toastConstructor()

    // 3. Manually mount the component object to an element 
    toast.$mount(document.createElement('div'))

    // 4. Add the element with the component object mounted to body
    document.body.appendChild(toast.$el)

    // 5. Mount the component object to Vue On the prototype of 
    Vue.prototype.$toast = toast
}

//  Expose the current plug-in 
export default obj

 Copy code 

Two 、com 2

tx

1. The size of the packaged applet .

The applet has a... Effect on size 2m The limitation of

Because applets have a... Effect on size 2m The limitation of , So sometimes small programs are too large , Can't upload , The solution is as follows ;

1, Look at the static resources introduced , Such as pictures , Can be compressed , Switch to png, Or put the back end into the background resources ,https introduce ,

2, Introduced js package css If there are resources on the packet network, they can be replaced with network resources ,

3, The imported plug-in package can be imported on demand , Don't introduce all ,

4, The reusable functions can be encapsulated , Reduce code redundancy

After the above processing, if it is still large, you can consider small program subcontracting , Reduce package size through subcontracting ,

api The address is as follows developers.weixin.qq.com/miniprogram…

In passing in app.json subpackages Field to declare the project subcontracting structure, you can subcontract the project , Reduce the size of the package , Subcontracting can be simple subcontracting and independent subcontracting

The main difference is that the independent subcontracting applet can run without the main package , It is worth noting that after subcontracting js Cannot reuse across packages , Independent subcontracting can improve the speed of page loading , There can be multiple independent subcontractors

2. vue Component to wechat Components

3. Input URL What happened after ?

4. Rendering DOM Why convert to a DOM Trees , Why not deal with strings directly .

image.png

From the network to the rendering engine HTML The file byte stream cannot be directly understood by the rendering engine , So turn it into For the internal structure that the rendering engine can understand , This structure is DOM.DOM Provide for the right to HTML Document structure Formalized expression .

DOM Is the expression HTML The internal data structure of , It will be Web Page and JavaScript Script connection get up , And filter some unsafe content .

HTML The parser does not wait , How much data does the network process load , The parser parses how much data .

HTML The parser does not wait until the entire document is loaded , It's how much data the network process loads ,HTML How much data does the parser parse .

image.png

5. Implementation and application scenario of anti chattering and throttling

6. http3.0 udp Agreement related

3、 ... and 、com 3

tujia

1. state in a by 0,React in componentDidMount Many times setState Post print state.a The value of is ? here render Function a What is the value of ? And in setTimeout Revision in China a And print , How much is the ?

answer : The initial value is printed for the first time 0. For the first time render Yes. 2. The code of the timer is printed with the modified value , here render The modified values are shown in .

2. Array shift, And which of the array methods are pure functions , What will change the original data ?

2.1) Will not change the original array

  • concat()--- Join two or more arrays , And return the result .
  • every()--- Checks whether each element of an array element is eligible .
  • some()--- Check whether any element in the array element meets the specified conditions .
  • filter()--- Detect array elements , And returns an array of all elements that meet the criteria .
  • indexOf()--- Search for elements in the array , And return to where it is .
  • join()--- Put all the elements of the array into a string .
  • toString()--- Convert an array to a string , And return the result .
  • lastIndexOf()--- Returns the last occurrence of a specified string value , Search from back to front in a specified position in a string .
  • map()--- Handle each element of the array by specifying a function , And return the processed array .
  • slice()--- Pick a part of the array , And return a new array .
  • valueOf()--- Returns the original value of the array object .

2.2) Will change the original array

  • pop()--- Delete the last element of the array and return the deleted element .
  • push()--- Add one or more elements... To the end of the array , And returns the new length .
  • shift()--- Delete and return the first element of the array .
  • unshift()--- Add one or more elements to the beginning of an array , And returns the new length .
  • reverse()--- Reverse the order of elements in an array .
  • sort()--- Sort elements of an array .
  • splice()--- For insertion 、 Delete or replace elements of an array .

2.1) Arrays can behave like stacks (LIFO) And queue (FIFO) Same operation

JavaScript The array of is an array that has the advantages of stack and queue itself global object . in other words JavaScript Arrays can behave like stacks (LIFO) And queue (FIFO) Same operation . This is also JavaScript The powerful operability of arrays .

Stacks and queues are It's a dynamic collection ,

  • In the stack , The element that can be removed is the one recently inserted . Stack implements last in first out .

    take push() and pop() Bind together , We can implement stack like behavior

  • In the queue , The element that can be removed is always the one that exists the longest in the collection . The queue implements a first in first out strategy .

    take shift() and push() Methods are combined , You can use arrays just like queues . That is, add items at the back of the array , Remove items from the front of the array

3. axios What factors need to be considered in packaging ?

answer : Default header configuration , And timeout To configure , And user authentication token To configure . With the request , Response configuration and error handling .

4. If we restrict the business in the interceptor, we can only initiate 5 A request , How to deal with . Here comes the second 6 When a request , Need to judge the previous 5 Whether any of the requests have been completed , And push the new request forward .

answer : My personal suggestion is to count the number of requests initiated through a variable , Add... To the request origination num++. Add... To the request response callback num--. then , Judge num How many and 5 The difference between the , Then go to supplement the follow-up request and come in . Subsequent requests can be unified and not sent out first , Put it in an array to maintain , Waiting to send .

But for now tcp Multiplexing . Multiple can be created at the same time tcp, Every tcp You can initiate multiple http request . There will be no such need .

5. Browser concurrency promotion ,http2 Multiplexing . You can create multiple TCP Connect , Every TCP You can initiate multiple HTTP request .

answer :juejin.cn/post/700180…

6. tujia This is mainly used RN To embed into multiple APP In the shell .

7. REACT And VUE diff Algorithm difference

7.1) The same thing :

Vue and react Of diff Algorithm , No cross level comparison , Just peer comparison .

7.2) Difference :

1.Vue Conduct diff when , call patch Patching function , Compare and give real DOM patch up

2.Vue Compare nodes , When the node element type is the same , however className Different time , Think of different types of elements , Delete and recreate , and react It is considered to be a node of the same type , Modify

① Vue List comparison of , From both ends to the middle , There are two pointers at both ends of the old set and the new set , Compare the two , If it matches, adjust the old set according to the new set , After each comparison , The pointer moves to the middle of the queue ;

② and react From left to right , Using elements index And identification lastIndex Compare , If meet index < lastIndex Just move the element , Delete and add are adjusted according to the rules ;

③ When a collection moves the last node to the front ,react Will move the front nodes backward in turn , and Vue Only the last node will be placed in the front , In this way ,Vue Of diff The performance is higher than react Of

8. let var const Differences between internal implementations

  1. var Declaration variable has variable promotion ,let and const No variable promotion
  2. let and const Declare chunk scope , and var This scope does not exist
  3. Under the same scope let and const Cannot declare a variable with the same name , and var Sure
  4. let、const There is a temporary dead zone

principle : var Will pre allocate memory space , Others don't . const Be careful

const Declared a constant of compound type , It stores a reference address , What is not allowed to change is this address , The object itself is variable . const If compound type data is declared , Its properties can be modified

9. Handwritten questions

Promise.reject(1).then().catch((e) => {
    return e
}).then((data) => {
    console.log(1, data)
}).catch((e) => {
    console.log(2, e)
})
 Copy code 

10. Handwritten questions

image.png

Be careful : This version is just thinking and can't be used :


const obj = {a: {b: {c:1} }, e:2};

function find(obj, str){
    let strArr  = str.split('.'); // [a,b,c]
    for(let i in obj){ // a , e
        if(obj[i] === strArr[0]){//a
            strArr.shift();
            if(typeof obj[i] === 'object'){
                find(obj[i], str)
            }else{
                return obj[i]
            }
        }
    }
};
 Copy code 

Reference resources

summary

版权声明
本文为[Infinite loop infinite]所创,转载请带上原文链接,感谢
https://chowdera.com/2021/09/20210909122358710r.html

随机推荐