[Front-end interview questions - JS articles]

1. What data types does javascript have and how are they stored?

Javascript data types are divided into basic data types and composite data types;
basic data types are: array, Boolean, string, symbol, undefined, null
composite data types: object, function
basic data types are stored in the stack
and reference data types are stored in in the pile

2. What are the methods of judging the data type? What's the difference?

1.typeof:
    typeof'';// string 有效
    typeof 1;// number 有效
    typeof Symbol();// symbol 有效
    typeof true;//boolean 有效
    typeof undefined;//undefined 有效
    typeof null;//object 无效
    typeof [] ;//object 无效
    typeof new Function();// function 有效
    typeof new Date();//object 无效
    typeof new RegExp();//object 无效
2.instanceof
    instanceof 是用来判断 A 是否为 B 的实例,表达式为:A instanceof B,如果 AB 的实例,则返回 true,否则返回 false。        在这里需要特别注意的是:instanceof 检测的是原型
3.constructor
当一个函数 F被定义时,JS引擎会为F添加 prototype 原型,然后再在 prototype上添加一个 constructor 属性
4.toString
toString() 是 Object 的原型方法,调用该方法,默认返回当前对象的 [[Class]] 。这是一个内部属性,其格式为 [object Xxx] ,其中 Xxx 就是对象的类型。

对于 Object 对象,直接调用 toString()  就能返回 [object Object] 。而对于其他对象,则需要通过 call / apply 来调用才能返回正确的类型信息。
    Object.prototype.toString.call('') ;  // [object String]
    Object.prototype.toString.call(1) ;   // [object Number]
    Object.prototype.toString.call(true) ;// [object Boolean]
    Object.prototype.toString.call(Symbol());//[object Symbol]
    Object.prototype.toString.call(undefined) ;// [object Undefined]
    Object.prototype.toString.call(null) ;// [object Null]
    Object.prototype.toString.call(newFunction()) ;// [object Function]
    Object.prototype.toString.call(newDate()) ;// [object Date]
    Object.prototype.toString.call([]) ;// [object Array]
    Object.prototype.toString.call(newRegExp()) ;// [object RegExp]
    Object.prototype.toString.call(newError()) ;// [object Error]
    Object.prototype.toString.call(document) ;// [object HTMLDocument]
    Object.prototype.toString.call(window) ;//[object global] window 是全局对象 global 的引用


3. Tell me about your understanding of the event loop?

Javascript is a single-threaded language, which means that only one thing can be done at the same time, but this does not mean that single-threaded is blocking, and the way to achieve single-threaded non-blocking is the event loop. In Javascript, all
tasks can be divided into

  • Synchronous tasks: Tasks that are executed immediately. Synchronous tasks generally enter the main thread directly for execution
  • Asynchronous tasks: tasks executed asynchronously, such as ajax network requests, setTimeout timing functions, etc.

Asynchronous tasks can also be subdivided into microtasks and macrotasks

  • A microtask is a function that needs to be executed asynchronously. The execution time is after the execution of the main function ends and before the end of the current macro task
  • The time granularity of macro tasks is relatively large, and the execution time interval cannot be precisely controlled. It does not meet some high real-time requirements.

4. Tell me about your understanding of BOM, what are the core of BOM? what is the role

BOM (Browser Object Model) , the browser object model, provides objects that interact with the browser window independently of the content

Its function is to do some interactive effects with the browser, such as how to go back, forward, refresh the page, change the browser window, scroll the scroll bar, and obtain some customer information such as: browser brand version, screen resolution

The entire content of the browser can be regarded as DOM, and the entire browser can be regarded as BOM

The core object of Bom is window , which represents an instance of the browser.
In the browser, the window object has a dual role, that is, an interface of the browser window and a global object.
Therefore, all variables and functions declared in the global scope Will become the properties and methods of the window object

The navigator object is mainly used to obtain browser properties and distinguish browser types. There are many attributes, and the compatibility is more complicated

screen saves purely client capability information, that is, information about the client display outside the browser window, such as pixel width and pixel height

The history object is mainly used to operate the history of the browser URL, which can be forwarded, backward, or redirected to the specified URL through parameters

5. What is the difference between Bind, call and apply? How to implement a bind method?

call, apply, and bind methods can change the this point of the function

  • The function will be executed immediately after the call method apply is called, and the bind method will not execute the function immediately
  • The call method and bind method are followed by a parameter list, and the parameter data of apply is an array

6. How to understand closure? What is the application scenario of closure?

The internal function that can access the variables in the external function.
In JS, only the sub-functions inside the function can read the local variables. The
closure is the bridge connecting the inside of the function with the outside of the function, allowing the outside to access the internal variables of the function.
Local variables are often Residing in memory can avoid the use of global variables, prevent global variable pollution, and
cause memory leaks. Every time an external function is executed,
the reference address of the external function is different, and a new address will be created
. Application scenario:

  • function nesting
  • An inner function references a variable of an outer function
  • return inner function as return value

7. Tell me about your understanding of the difference between synchronous and asynchronous?

Synchronization:
The idea of ​​synchronization is: all operations are completed before returning to the user. In this way, the user waits online for too long, giving the user a feeling of being stuck (that is, during the system migration, when the migration is clicked, the interface does not move, but the program is still executing, and the feeling of being stuck). In this case, the user cannot close the interface. If it is closed, the migration process will be interrupted.

Asynchronous:
Put the user request into the message queue and give feedback to the user. The system migration program has started, and you can close the browser. Then the program slowly writes to the database. This is asynchronous. But the user does not feel stuck, and will tell you that your request system has responded. You can close the interface now.

8. What is an event proxy?

Event proxy, also known as event delegation, is a design idea in web design, that is, to bind the events of one or a group of elements (target elements) to parent or ancestor elements. It is the outer element, not the target element, that actually binds the event.

When the event responds to the target element, it will trigger the binding event of its outer element through the event bubbling mechanism, and then execute the function on the outer element.

9. What is anti-shake and throttling, and what is the difference? How to achieve?

Anti-shake function (debounce)

Function: Execute the callback after N seconds after the event is triggered, and restart the timing if it is triggered within N seconds.
For example, for an input box, after the application implements the anti-shake function, when the user continues to input content, the function will always be triggered, and no request will be sent. Only when the user does not perform an input operation within a specified period of time N, a request will be sent. If the input content is interrupted within N seconds, and the intermittent time is less than the specified time N, the timing will be restarted and the request will not be sent.
This reduces the number of requests sent, improves performance and improves user experience.

// func是用户传入需要防抖的函数
// wait是等待时间,若不传参,默认50ms
// 因为闭包,timer将一直在内存中
const debounce = (func, wait = 50) => {
    
    
    // 缓存一个定时器
    let timer = null;
    // 返回的函数是每次用户实际调用的防抖函数
    return (...args) => {
    
    
        // 如果已经设定过定时器了就清空上一次的定时器
        if (timer) clearTimeout(timer);
        // 开始一个新的定时器,延迟执行用户传入的方法
        timer = setTimeout(() => {
    
    
            func.apply(this, args);
        }, wait);
    };
};

Throttle function (throttle)

Function: It is stipulated that the function can only be triggered once in a unit time. If the function is triggered multiple times within this unit time, only one time will take effect

// func是用户传入需要防抖的函数
// wait是等待时间,若不传参,默认50ms
// 因为闭包,falg将一直在内存中
const throttle = (func, wait = 50) => {
    
    
    // 定义falg,初试为true
    let flag = true;
    // 返回的函数是每次用户实际调用的节流函数
    return (...args) => {
    
    
        if (flag) {
    
    
            // 如果flag为true,则执行定时器
            setTimeout(() => {
    
    
                func.apply(this, args);
                // 函数执行完毕后,将flag改回true
                // 以便下次再执行
                flag = true;
            }, wait);
        }
        // 因为定时器是异步任务,定时器执行后,立刻将flag关闭
        // 在等待延时时间时,阀门始终关闭,不会一直执行函数
        flag = false;
    };
};

10. Understanding of scope chain?

The scope is divided into global scope and function scope (before ES6, JavaScript did not have block-level scope, only global scope and function scope. The arrival of ES6 provides us with block-level scope, which can be added through the new command let and const to reflect.)

  • Global scope: It can be positioned at any position, and the built-in property of window is the global scope

  • Function scope: It can only be accessed in the function body, which is the private scope, and they are all stack memory

Scope is code execution to open up stack memory. The biggest use of scope is to isolate variables. Variables with the same name in different scopes will not conflict.

11. Understanding of prototype and prototype chain?

Prototype : Each constructor has a prototype attribute, which is called the display prototype of the function.
After the constructor is instantiated or the object has a __proto__ attribute, it is called the implicit prototype of the object. The subsequent prototype chain is Find properties by proto.
Prototype chain : When we access a certain property of an object, we will first search from the current object, if not found, continue to search in the proto hermit prototype of the object, if not found, continue to the prototype of the superior object Search until the top-level Object object is found. If it is not found, it returns undefined. This chain relationship of searching for properties through the __proto__ implicit prototype of the object is called the prototype chain.

12. What are the Javascript local storage? Differences and usage scenarios?

  • Cookie
    Cookie refers to the data stored on the user's local terminal by some websites in order to identify the user's identity.
    It is to solve the problem caused by HTTP statelessness.
    A cookie is small text data, no more than 4k, and a cookie has a validity period and security.
    The cookie will be sent in every request. If you do not use HTTPS and encrypt it, the information stored in it can be easily stolen, resulting in security risks.

  • localStorage
    features:

    • Life cycle: persistent local storage, unless the data is actively deleted, the data will never expire
    • Stored information is shared within the same domain
    • When this page operates (add, modify, delete) localStorage, this page will not trigger the storage event, but other pages will trigger the storage event.
    • Size: 5M
    • localStorage essentially reads strings. If there is a lot of storage content, it will consume memory space and cause the page to become stuck.
    • Restricted by same-origin policy
  • sessionStorage
    The usage of sessionStorage and localStorage is basically the same. SessionStorage means that once the page is closed, sessionStorage will delete the data.

the difference

  • 1. Life cycle (valid time):
    Cookie: You can set the expiration time. If it is not set, the default is to close the browser and expire. localStorage: Unless manually cleared, it will be saved permanently.
    sessionStorage: only valid in the current web page session, and will be cleared after closing the page or browser.

  • 2. Storage size
    cookie: about 4KB localStorage and sessionStorage: can save 5MB of information.

  • 3. HTTP request
    cookie: It will be carried in the HTTP header every time. If you use cookies to save too much data, it will cause performance problems.
    localStorage and sessionStorage: only saved in the client (that is, the browser), and do not participate in communication with the server.

  • 4. Ease of use cookie: It needs to be packaged by the programmer. The original
    cookie interface is not friendly.

  • 5. Interaction between data and server
    Cookie data will be automatically transmitted to the server, and the server can also write cookies to the client.
    SessionStorage and localStorage will not automatically send data to the server, but only save it locally.

Application Scenario

  • From the perspective of security, because every http request will carry cookie information, which wastes bandwidth virtually, so cookies should be used as little as possible. In addition, cookies need to specify a scope, and cross-domain calls cannot be made, which has many restrictions. But for identifying user login, cookie is better than storage. In other cases, you can use storage, just use storage.

  • Storage kills cookies in seconds on the size of stored data, and cookies are rarely used now.

  • The only difference between localStorage and sessionStorage is that it is permanently stored in the browser, and the other is that the information is cleared when the webpage is closed. localStorage can be used to pass parameters on the page, and sessionStorage is used to save some temporary data to prevent users from losing some parameters after refreshing the page.

おすすめ

転載: blog.csdn.net/zz130428/article/details/130201322