编程知识 cdmana.com

Bat and major Internet companies 2020 front-end written test interview questions -- JavaScript

1. Please talk about Cookie Advantages and disadvantages

advantage : High scalability and availability

  1. Data persistence .
  2. No server resources required . Cookie Stored on the client and read by the server after sending .
  3. Configurable expiration rules . control cookie Life cycle , Make it not always effective . The thief is likely to get an expired cookie .
  4. simplicity . Lightweight structure based on text .
  5. Through good programming , Control is kept in cookie Medium session Size of object .
  6. Through encryption and secure transmission technology ( SSL ), Reduce cookie The possibility of being cracked .
  7. Only in cookie Store sensitive data in , Even if stolen, there will be no significant loss .

shortcoming :

  1. Cookie Restrictions on quantity and length . Number : Of each domain cookie The total is limited . a) IE6 Or lower version at most 20 individual cookie b) IE7 And later versions can end up with 50 individual cookie c) Firefox most 50 individual cookie d) chrome and Safari There are no hard limits length : Every cookie Length not exceeding 4KB ( 4096B ), Otherwise it will be cut off .
  2. Potential security risks . Cookie Could be intercepted 、 Tampering . If cookie Be intercepted , It's possible to get all of session Information .
  3. The user is configured to disable . Some users have disabled browser or client device acceptance cookie The ability of , So it limits this function .
  4. Some states cannot be saved on the client side . for example , To prevent duplicate submission of forms , We need to save a counter on the server side . If we save this counter on the client side , Then it doesn't work .

2.Array.prototype.slice.call(arr,2) The purpose of the method is to :

utilize Array Archetype slice Method , Use call First argument to function , Let the... In this method this Point to arr, And pass the parameters 2, Actually equal to arr.slice(2), That is, from the subscript to 2 Start to intercept to the end .

3.JavaScript What are the data types of ?

Basic data type :String,Boolean,Number,Undefined, Null

Reference data type :Object(Array,Date,RegExp,Function)

So here comes the question , How to determine whether a variable is an array data type ?

Method 1 . Judge whether it has “ Array property ”, Such as slice() Method . You can define this variable by yourself slice Method , So sometimes it doesn't work Method 2 .obj instanceof Array In some IE The version is not correct Method 3 . There are loopholes in both methods , stay ECMA Script5 A new method is defined in Array.isArray(), Ensure compatibility , The best way is as follows :

if(typeof Array.isArray==="undefined")
{
  Array.isArray = function(arg){
        return Object.prototype.toString.call(arg)==="[object Array]"
    }; 
}

4. Let's just say what the browser's local storage looks like

in general , Browser storage is divided into the following categories : 1、Cookie Storage , Plaintext , Size limit 4k etc. 2、localStorage, One of the ways of persistent storage , You don't have to transfer between the two ends , And the limited size is 10M 3、sessionStorage, Session level storage mode , Browser shut down immediately data loss 4、indexDb, Browser side database

5. Prototype chain :

Prototype chain is composed of prototype objects , Every object has proto attribute , Points to the prototype of the constructor that created the object ,proto Connect objects to form a prototype chain . Is a Limited chain of objects used to implement inheritance and sharing properties .

Property lookup mechanism : When looking for an object's properties , If the instance object itself does not have this property , Then go up the prototype chain , Output when found , When there is no , Then continue to search up the prototype chain , Up to the top prototype object Object.prototype, If still not found , The output undefined;

Property modification mechanism : Only the properties of the instance object itself will be modified , If it doesn't exist , Then add the attribute , If you need to modify the properties of the prototype , You can use : b.prototype.x = 2; But this will cause the properties of all instances inherited from the object to change .

6. The variable object

The variable object , Is part of the execution context , Can be abstracted as one Data scope , In fact, it can also be understood as a simple object , It stores all the Variable and function declarations ( Does not contain function expression ). The object of activity (AO): When the context of the variable object is active EC when , Called active object .

7. Scope chain

We know , We can access the parent or even global variables in the execution context , This is the credit of the scope chain . A scope chain can be understood as a list of objects , contain Parent and own variable objects , Therefore, we can access the variables or functions declared in the parent through the scope chain . It's made up of two parts :

  • [[scope]] attribute : Point to parent variable object and scope chain , Including the parent [[scope]] and AO
  • AO: Self active object such [[scopr]] contain [[scope]], And then from top to bottom Chain scope .

8. Closure

Closures belong to a special scope , be called Static scope . Its definition can be understood as : Parent function destroyed Under the circumstances , Of the returned subfunction [[scope]] There are still univariate objects and scope chains at the parent level , So you can continue to access the parent variable object , Such a function is called a closure . Closure is a classic problem : Of multiple subfunctions [[scope]] Both point to the parent at the same time , Is fully shared . Therefore, when the parent variable object is modified , All subfunctions are affected . solve : Variables can be The form of function parameter Pass in , Avoid using the default [[scope]] Upward search Use setTimeout The parcel , Passed in through the third parameter Use Block level scope , Make variables properties of their own context , Avoid sharing

9. script Introduction mode :

html static state <script> introduce js Dynamic insertion <script> <script defer>: Delay loading , Execute after element parsing <script async>: Load asynchronously , However, element rendering is blocked during execution

10. Copy of object

Shallow copy : Copy reference objects as assignments , Still point to the same address , When modifying, the original object will also be affected Object.assign Expand operator (...)

Deep copy : Copy a new object completely , When modified, the original object is no longer affected JSON.parse(JSON.stringify(obj)): The fastest performance When an object has a circular reference , Report errors When the value is a function 、undefined、 or symbol when , Cannot copy Recursively assign values one by one

11.new Operator execution

New build an object Link to prototype : obj.proto = Con.prototype binding this: apply Return to new object ( If the constructor has its own retrun when , Then return the value )

12.instanceof principle

Can be found in the Prototype object chain The prototype Property points to Prototype object , Just go back to true. namely :

// __proto__:  Represent prototype object chain 
instance.[__proto__...] === instance.constructor.prototype
// return true

13. Type judgment

Judge Target The type of , Single use typeof Not completely satisfied , It's not bug, The essential reason is JS The theory that all things are objects . So when it comes to really perfect judgment , We need to differentiate : Basic types (null): Use String(null) Basic types (string / number / boolean / undefined) + function: Use it directly typeof that will do Other reference types (Array / Date / RegExp Error): call toString According to [object XXX] Judge Very stable judgment package :

let class2type = {}'Array Date RegExp Object Error'.split(' ').forEach(e => class2type[ '[object ' + e + ']' ] = e.toLowerCase()) 
function type(obj) {
    if (obj == null) return String(obj)
    return typeof obj === 'object' ? class2type[ Object.prototype.toString.call(obj) ] || 'object' : typeof obj
}

14. modularization

Modular development is an indispensable part of modern development , It greatly improves the maintainability of the project 、 Scalability and collaboration . Usually , We Use in browser ES6 Modular support for , stay Node Use in commonjs Modular support for . classification : oes6: import / export ocommonjs: require / module.exports / exports oamd: require / defined require And import The difference between orequire Support Dynamic import ,import I won't support it , Under proposal (babel Lower support ) orequire yes Sync Import ,import Belong to asynchronous Import orequire yes Value copy , Changes in export values do not affect import values ;import Point to Memory address , Import values change with export values

15. Anti shake and throttling

Anti chattering and throttling function is one of the most commonly used High frequency trigger optimization mode , Can be of great help to performance . Shake proof (debounce): Optimize multiple high frequency operations to be performed only at the last time , The commonly used scenario is : User input , Just do one input check after the input is finished .

function debounce(fn, wait, immediate) {
    let timer = null

    return function() {
        let args = arguments
        let context = this

        if (immediate && !timer) {
            fn.apply(context, args)
        }

        if (timer) clearTimeout(timer)
        timer = setTimeout(() => {
            fn.apply(context, args)
        }, wait)
    }
}

throttle (throttle): Once every other time , That is, reduce the frequency , Optimize high frequency operation to low frequency operation , Commonly used scenarios : Scroll bar events perhaps resize event , Usually every 100~500 ms Only once .

function throttle(fn, wait, immediate) {
    let timer = null
    let callNow = immediate
    
    return function() {
        let context = this,
            args = arguments

        if (callNow) {
            fn.apply(context, args)
            callNow = false
        }

        if (!timer) {
            timer = setTimeout(() => {
                fn.apply(context, args)
                timer = null
            }, wait)
        }
    }
}

In order not to affect the reading experience , Share only part of the interview questions , More interview questions and answers can be 【 Click on the I 】 Read and download ~ Free to share , It's a kind of gratitude

16. The function is coriolized

In a function , Fill in a few parameters first , And then return to the technique of a new function , The currification of functions . It can be used without invading functions , For the function Preset general parameters , For multiple repeated calls .

const add = function add(x) {
	return function (y) {
		return x + y
	}
}
const add1 = add(1)
add1(2) === 3
add1(20) === 21

17.get Error in the length of request parameters

myth : We often say get There is a limit to the size of the request parameter , and post The requested parameter size is unlimited . actually HTTP The agreement never provided for GET/POST What is the request length limit for . Yes get The request parameters are limited by the source and browser or web The server , The browser or web The server limits url The length of . To clarify the concept , We have to emphasize again the following points : HTTP agreement Not specified GET and POST The length limit of GET The maximum length of the display is because The browser and web The server limits URI The length of Different browsers and WEB The server , The maximum length of the limit is not the same To support IE, The maximum length is 2083byte, If only support Chrome, Then the maximum length 8182byte

18. Add get and post The difference between requests in caching

post/get The difference between the requests of , I will not repeat the details . Add one more get and post The difference in caching : get The request is similar to the search process , Users get data , You don't have to connect to the database every time , So you can use caching . post Different ,post What we do is to modify and delete , So you have to interact with the database , So you can't use caching . therefore get Requests are suitable for request caching .

19. Let's talk about the front-end events in the stream

HTML China and javascript Interaction is event driven , For example, mouse click event onclick、 Page scrolling Events onscroll wait , You can add event listeners to documents or elements in documents to subscribe to events . Want to know when these events are called , We need to know something about “ Flow of events ” The concept of . What is event flow : The event flow describes the order in which events are received from the page ,DOM2 Level event flow consists of the following stages . Event capture phase At the target stage Event bubbling stage addEventListener:addEventListener yes DOM2 Class events, the operation of the specified event handler , This method receives 3 Parameters : Event name to process 、 Function as an event handler and a Boolean value . Finally, if the Boolean parameter is true, Indicates that the event handler is called during the capture phase ; If it is false, Indicates that the event handler... Is called during the bubbling phase . IE Only support incident bubbling .

20. How to make an event bubble first and then capture

stay DOM Standard event model , It's catching before bubbling . But if you want to achieve the effect of bubble first and capture later , For the same event , Sniffing, catching and bubbling , Corresponding to the corresponding processing function , A capture event was detected , Put it on hold , Until the bubble event is captured before the capture is performed .

21. Let's talk about event delegation

brief introduction : Event delegation refers to , Not in the place where the incident happened ( direct dom) Set monitor function on , Instead, set the listener function on its parent element , Bubbling through events , The parent element can listen to the triggering of events on the child element , By judging the elements of the event DOM The type of , To make a different response . give an example : The classic one ul and li Tag event monitor , For example, when we add events , Use event delegation mechanism , Not in li Add... Directly to the label , But in ul Add... To the parent element . benefits : More suitable for dynamic element binding , The newly added child elements will also have monitor functions , There can also be event triggering mechanisms .

In order not to affect the reading experience , Share only part of the interview questions , More interview questions and answers can be 【 Click on the I 】 Read and download ~ Free to share , It's a kind of gratitude

版权声明
本文为[Go with the wind]所创,转载请带上原文链接,感谢
https://cdmana.com/2020/12/20201224214750715e.html

Scroll to Top