preface

Summary of many common JS basic knowledge points, most of the articles on the network have seen a time. Planning again, there is no answer to any question, most of their search from the nuggets of quality articles. Because they are all piecemeal questions, looking for too many or roughly the same questions. Also take into account what copyright problem, hope forgive me! Hee hee lay a good foundation for his junior internship! Oneself must refuel!! Also sorted out for children in need ✨

JS based

101. What is the difference between toPrecision and toFixed and Math.round?

ToPrecision is used to deal with precision, counting from left to right from the first non-zero number.

ToFixed Is used to deal with the number of precision after the decimal point, starting at the decimal point and rounding off the precision at the end. The result is a character.

108. What is MVVM? How is it different from MVC? What is MVP?

MVC is an interaction mode that separates Model, View and Controller. Controller is mainly used to control the response operations of users and applications. When the page node changes, it performs operations through listening functions and changes the Model, and then notifies the View layer of updates.

The difference between MVP and MVC is that MVP uses presenter, whereas MVC uses observer mode to update the View when the Model layer changes. Because the View is not exposed to the Controller interface, it cannot control the update of the View. In this way, the View and Model layer are coupled together. MVP decouple the two. Presenter binds the View and Model together for synchronous updates, while MVVM automates MVP updates.

MVVM refers to Model, View and ViewMode, which are used to separate views from data. View refers to the View area, which is used for page rendering and displaying data. Model is used to store data and logical interaction functions of data. The ViewModel is the link connecting the two. When data changes, the ViewModel listens to the data changes and responds to the View to update the View. When the page node changes, the ViewModel responds to the Model to update the data. Update the View and Model synchronously with two-way data binding.

109. Vue bidirectional data binding principle?

MVVM two-way data binding, the application of data hijacking combined with subscriber publisher mode. First, listeners listen for data properties by hijacking getters and setters on individual properties via Object.defineProperty(), notifying subscribers when data changes, and triggering responsive listener callbacks to update the view. MVVM as a data interface will also have a parser, instructions for each element node scanning and parsing, and according to the template instruction to replace the data, initialize the page, binding the corresponding update function at the same time, the subscription data change, add to monitor data of subscribers, once the data have change notified update the view, it has realized the data update view change, View changes update two-way data binding of data.

110. Object. DefineProperty introduction?

The obect.defineProperty () method takes three arguments. The first argument is the object for which the attribute is to be defined, the second argument is the attribute for which the attribute is to be defined, and the third argument is the descriptor. The descriptor of the attribute has four attributes: Value (the value of the property), writable (writable), Enumerable (enumerable), and different (whether the property can be configured and modified).

111. What are the disadvantages of using Object.defineProperty() for data hijacking?

Some operations on data, such as modifying array data and adding attributes to objects, cannot be hijacked in this way. In Vue3.0, a proxy can be used to implement object proxy to achieve data hijacking. However, it is not compatible because it is an ES6 syntax.

112. What is the Virtual DOM? Why is Virtual DOM faster than native DOM?

When the page is updated, the cost of updating the native DOM is relatively high, so JS code is used to generate a virtual DOM. When the data is updated, a new virtual DOM will be generated, and then compared with the previous virtual DOM. Diff algorithm is used to compare the differences between the two. Then, the differences of the corresponding nodes are combined into the native DOM tree to complete the update.

Using virtual DOM can save performance, improve operation efficiency, and save overhead. Avoid backflow and redraw from changes made with native DOM. Improve maintainability at development time.

113. How do I compare the difference between two DOM trees?

Diff algorithm is used to compare the difference between two DOM trees. The time degree of complete comparison between two DOM trees is O (n^3). In the front-end process, we generally do not move elements across levels. In order to minimize the time degree, we compare nodes at the same level of the two trees. The two trees are first traversed in depth and each node is numbered. When traversing a DOM tree in depth, one node is compared to another, and any differences are saved to an object.

114. What is requestAnimationFrame?

RequestAnimationFrame is an API that allows browsers to execute js animations. We know that animations are generated frame by frame. If we use timer to execute animations, it will be executed after the specified time because timer is an asynchronous function. The asynchronous queue must wait for the synchronous task to complete before executing the callback function, which cannot guarantee the smoothness of the animation. This can be done with requestAnimationFrame, which takes a parameter to the animation execution function, for example

function animation(){
    var div = document.querySelector('.box');
    div.style.width = parseInt(div.style.width) + 1 + 'px';
    if(div.style.width < 200){
        requestAnimationFrame(animation)
    }
}
requestAnimationFrame(animation);
Copy the code

115. Tell me what you think of Webpack

The main purpose of using Webpack is to simplify the management of project dependencies. It regards all resources as a module and all logical codes as a whole. Starting from the entry of packaging, the dependencies required by the project are processed by loader and plugin, and then output a JS code that can be resolved by the browser. Webpack has four core concepts, namely Entry, Output, Loader and Plugin.

Entry refers to the entry point where a project is packaged and where all dependent files are found.

Output is the exit of the project package, packaged into a compatible JS code with a default location of ‘./dist’.

Loader belongs to the compiler of Webpack, which is used to package non-javascript files. When configuring loader, test is used to specify which files ending with suffixes are used to package, and the content is regular expression. The use attribute indicates which loader is used to preprocess the test file, such as CSS-loader and style-loader.

Plugins can be used for a wider range of functions, such as file compression, optimization, and server building. To use a plug-in, install it with NPM and then add it to the configuration file for use.

116. The offsetWidth/offsetHeight, clientWidth/clientHeight scrollWidth/scrollHeight difference?

OffsetWidth /offsetHeight returns a read-only property containing the element’s border, padding, content, and scrollbar.

OffsetLeft /offsetTop returns the distance to the left and the distance to the top of the element from its nearest parent element offsetParent.

ClientWidth /clientHeight returns a read-only property of the element’s internal width, content+padding.

ClientLeft /clientTop returns the width of the top/left border of the element.

ScrollWidth /scrollHeight Read-only, returns the actual width and height of the element, including the rolled height/width.

ScrollLeft /scrollTop returns the top/left distance from which the element is rolled.

117. What do you understand about functional programming?

Functional programming is a programming specification that implements and manipulates content on a page through a series of function calls.

118. How to implement asynchronous programming?

Asynchronous programming implementations can be divided into the following categories:

  1. Callback function form: Asynchronous programming is implemented through callback functions, so that different tasks are executed in sequence, and the next one will be executed only after the previous one is completed. However, the disadvantage is that when the number of tasks is large, layers of nested callback hell will occur, resulting in complex code redundancy and difficult to maintain.
  2. Promise object: Promise can solve the callback hell problem by creating a Promise instance object using new and accepting a callback function as an argument. The function accepts two state functions, resolve and Reject, indicating that the state changes from the wait state to the successful and failed state. The returned Promise object can be chain-called through.then to implement the sequential function operation.
  3. Generator, which transfers execution rights out during the execution of a function and back outside the function. We transfer execution out when we encounter an asynchronous function and back when the asynchronous function is finished executing. This allows us to write asynchronous statements synchronously inside functions.
  4. Async and await: An ordinary function is preceded by async to transform the function into an asynchronous function that returns a promise object. When an await statement is executed inside the function, if the statement returns a promise object, the execution will proceed after the current statement is completed.

119. Js animation and CSS animation difference and corresponding implementation

CSS animations are relatively simple, and browsers have a good handle on CSS animations, but they are not easy to control, flexible, and not compatible enough.

JS animation can well control the flexibility of animation, and easy to control, and can control the operation of a single frame, powerful, but large amount of code, can be used for large animation projects, if small animation or CSS is more appropriate.

Error in length of get request parameters

Actually get request content length does not limit parameters, the length of the same post and also there is no limit to the length, but get requests are generally through the parameter on the url address, and through the browser and server url length is limited, so get request the length will be limited, usually different browser to the url length limit.

121. What is the difference between A URL and a URI?

A URL is a Unified resource locator (URL), and a URI is a unified resource identifier (URI). It is an abstract concept that uniquely identifies a resource. A URL is a TYPE of URI that uniquely identifies resources by address. URN is a universal resource name. Similarly, IT is a TYPE of URI that identifies a resource by name.

122. Cache differences between GET and POST requests

Get is a look-up process for retrieving data, so instead of submitting a request to the server every time, it can use caching.

Post is different in that it is generally used to add and modify functionality, so it must request the server for each commit, must interact with the database, and cannot use caching.

Cache only applies to requests that do not modify or add server-side data. Generally, GET is a lookup request and does not update the database. Therefore, GET is suitable for caching data, while POST updates the database and therefore cannot take advantage of caching.

123. Lazy loading and preloading of images

Lazy loading of images refers to a function of lazy loading. In the process of page loading, all images in the page are not loaded at one time, but are loaded when the page scrolls to the current position, which can reduce the pressure of page loading and make the page smoother.

Image preloading means that the image is loaded before the page is loaded and saved locally. When rendering is needed, the image is directly obtained from the local, saving the image loading time. Preloading can use the Image to create an instance object, and the Image can be preloaded by setting the SRC attribute for the Image object. Lazy loading and preloading both improve the performance of web pages, one is delayed or even not loaded, one is loaded in advance, lazy loading has a certain relief on the server side, while preloading increases the server side pressure.

124. What is the difference between mouseover and MouseEnter?

The difference between the two is whether they support bubbling, which is similar in that both are triggered when the mouse moves over an element. Mouseenter does not support bubbling, so mouseover and Mouseout events are triggered on the parent element when the mouse moves over the child element, but mouseEnter and Mouseleave events are not.

125. js drag function implementation

Three events are involved: mousedown, Mousemove, and Mouseup

The mouseDown event function first gets the position of the mouse click from the event object, event.clientX and event.clientY, as well as the initial position of the dragged element, offsetLeft and offsetTop. And create a mouse movement event mousemove. In this event function, assign the position of the mouse – the initial position of the mouse + the initial position of the element to the element’s position style. Then, in the create mouse lift event mouseup function, cancel the mouse press event and mouse move event to clear the state.

126. Why use setTimeout to implement setInterval? How do you simulate it?

SetInterval timer is each by a certain time to perform a function, but is, in fact, each task after a certain time to add this event to the queue, awaiting execution stack of after the event has been completed from the task queue for press events into the execution stack, so you can’t guarantee every once in a while to perform an event. So you can use setTimeout method to execute, the principle is to use recursive way to call the function to execute setTimeout.

function myInterval(fn, wait){
    var timer = {
        flag: true
    };
    function interval(){
        if(timer.flag){
            fn();
            setTimeout(interval, wait);
        }
    }
    setTimeout(interval, wait);
    return timer;
}
Copy the code

127. What should be noticed about let and const?

  1. Variables declared by lets and const cannot be promoted.
  2. Let and const have their own separate scope.
  3. Duplicate declarations are not allowed. Duplicate declarations will cause an error.
  4. A variable declared by const is not allowed to change its value; const is a constant.

128. What are REST parameters?

Rest arguments (of the form... Variable name), used to get extra arguments to a function.Copy the code

129. What is a tail call and what are the benefits of using it?

Tail-call means that the last step of a function calls another function. Our code execution is based on the execution stack, so when we call another function within a function we preserve the current execution context, and when we call a function in the last step we push the new execution context onto the execution stack. Because it is called at the last step, we can no longer retain the current execution context, thus optimizing memory, which is the benefit of the last call.

130. What is the Symbol type?

The Symbol function cannot use the new command, otherwise an error will be reported.

The Symbol function can take a string as an argument representing a description of an instance.

Symbol as attribute name does not appear in for.. And in the for… Of the.

131. Set and WeakSet structures?

A Set, as a data structure, is similar to an array in that it guarantees that the elements of the array are unique and have no duplicate values.

WeakSet is similar to Set, which is also a collection of non-repeating values, but its members can only be objects, not other types of values. It represents a weak reference that cannot be recovered by garbage collection mechanism.

132. Map and WeakMap structure?

A Map is a data structure, similar to an object, in the form of key-value pairs, but the range of keys can be not only strings, but also any type of value.

WeakMap is similar to Map, but the key can only be objects, not other types of structures, and the object to which the key name points cannot be included in the garbage collection mechanism.

133. What is Proxy?

Proxy means to modify the behavior of the default operation. It is equivalent to setting a layer of “interception” before the target object. Any operation on the target object must be filtered and rewritten, which is equivalent to making changes on the language level, namely metaprogramming.

134. Reflect object creation purpose?

1) Reflect some internal methods of Object, such as Object.defineProperty. The main thing is to optimize the methods inside the language.

DefinePropery (obj,name,desc) cannot define a property, while reflect.definedProperty (obj,name,desc) returns false.

Reflect.has(name) and reflect.deleteProperty (obj,name) can be substituted for the former: name in obj and delete obj[name].

4) Reflect method and Proxy method correspond one to one. The main purpose is to realize the interface consistency between ontology and proxy, and facilitate users to operate ontology through proxy.

135. Lookup methods introduced by the require module?

If the require import path does not introduce a suffix, first check whether there is a JS file with the same name in the path. If there is no JS file with the same name, go to the index.js folder. Json in the current folder will look for the entry file in the main option. If the specified entry file does not exist, an error will be reported.

When require does not import a path or suffix, node.js will default to importing system modules and will look for js files with the same name in node_modules. If there is no js file with the same name, it will look for a folder with the same name and find the index.js file with the same name. If there is no index.js file, look for entry files in the package.json option in that folder. If there is none, an error will be reported.

136. What are Promises/A+ Promises?

Promises objects are A solution to asynchronous programming. Promises/A+ specification is A code specification for JavaScript Promises that specifies some programming standards for Promises. Promise is a constructor that creates a Promise instance object, takes a callback function as an argument, and returns a Promise instance with three states: Pending, Resolved, and Rejected. The state can only change from “Resolved” to “Volatile” or “Rejected”. After the change, the state will be frozen and will not change to any other state. Switch the state after the asynchronous task by calling the Resolved or Rejected methods, return a Promise object, and define the Resolved and Rejected callback functions through a. Then chain call.

Write a Promise by hand

function myPromise(fn){ var self = this; this.state = 'penging'; this.value = null; this.resolvedCallback = []; this.rejectedCallback = []; function resolve(value){ if(value instanceof myPromise){ return value.then(resolved, rejected); } setTimeout(() => { if(self.state == 'pending'){ self.value = value; self.state = 'resolved'; self.resolvedCallback.forEach(callback => { callback(value); }) } }, 0) } function reject(value){ setTimeout(() => { if(self.state == 'pending'){ self.value = value; self.state = 'rejected'; self.rejectedCallback.forEach(callback => { callback(value); })}}, 0)} // Pass two methods into the function try{fn(resolve, reject); } catch(e){ rejecte(e); }; } myPromise. Prototype. Then = function(onResolved, onRejected){ As these two parameters are optional onResolved = typeof onResolved == 'function'? onResolved : function(value){ return value; } onRejected = typeof onRejected == 'function' ? onRejected : function(error){ throw error; } / / if it is a wait state if (this. State = = 'pending') {this. ResolvedCallback. Push (onResolved); this.rejectedCallback.push(onRejected); If (this.state == 'resolved'){onResolved(this.value); } if(this.state == 'rejected'){ onRejected(this.value); }}Copy the code

138. How do I check the minimum font size supported by the browser?

You can set the DOM font to a certain font size and then pull the font out, if successful, indicating support.

139. How to make JS code Error statistics?

Use the window.error event

140. Singleton Pattern What is a pattern?

Juejin. Cn/post / 684490…

141. What is the strategic pattern?

Juejin. Cn/post / 684490…

142. What is the proxy mode?

Juejin. Cn/post / 684490…

143. What is the mediator model?

Juejin. Cn/post / 684490…

144. What is the adapter mode?

Adapter pattern is used to solve the two interfaces is not compatible with cases, the interface for packaging adapter and do not need to change the original interface, and generally applies when too much interface is applied to the application to modify the original interface is not very convenient, so that you can use the adapter to the interface for packaging output, for example, we need to get a formatted time, However, if the original time interface cannot be modified, it can be encapsulated by an adapter.

145. What is the difference between the Observer model and the publish-subscribe model?

The publish-subscribe pattern belongs to the observer pattern in the broad sense. In the observer pattern, the observer needs to subscribe to events directly, and when the target sends out content changes, the observer will be directly informed to respond.

Publish-subscribe pattern in a dispatching center, can realize the decoupling between the publisher and subscribers, namely after the publisher publish event, dispatching center will receive events on the one hand, to the publisher, and then to the subscriber, the subscriber needs to subscribe to events of dispatching center, such late decoupling is conducive to the maintainability of the code.

146. What is the life cycle of Vue?

The Vue life cycle refers to the sequence of components from creation to destruction. With the hook functions that Vue provides at various stages of the lifecycle, we can perform some operations at each stage.

147. What are the life stages of Vue?

  1. The beforeCreate hook function is generated when the Vue component is initialized. The beforeCreate hook function is generated when the Vue component is initialized. The beforeCreate hook function is generated when the Vue component is initialized.
  2. Created hook function: triggered when the instance is created, the component is not mounted to the page, but can access the data and methods properties. This is usually the time to get the initial data for the page.
  3. BeforeMount hook function: Triggered before the component is mounted to the page, at which point the corresponding template is found and compiled into the render function.
  4. Mounted hook: When a component is mounted to a page, DOM elements can be retrieved from the DOM API.
  5. BeforeUpdate hook function: Triggered when reactive data or nodes are updated before the virtual DOM has been rendered.
  6. Updated hook function: Fires when the virtual DOM is rerendered.
  7. BeforeDestory hook function: called before instance destruction, used to destroy timers, unbind global events, etc.
  8. Destoryed hook function: called after the instance is destroyed, after which all listening events of the instance are unbound and all subinstances are eliminated.

148. How are parameters passed between Vue components?

Juejin. Cn/post / 686154…

149. Differences between computed and Watch?

Computed is a calculation of attributes, and when a value needs to be computed by a series of variables or by listening for an event, it can be computed by attributes, and the resulting value can be used in functions.

Watch is to monitor the value of a certain data. When this data changes, it will affect other data and call the execution function. The summary is that computed affects one data, while watch affects many data.

150. Navigation hook functions in vue-Router

The navigation hook function in vue-Router can act as a route guard.

  1. Global navigation hooks: BeforeEach and afterEach are used before and afterEach route, respectively. Take the beforeEach example, it receives three parameters: to, from, next. To indicates the route to enter, from indicates the route to leave. Next if the parameter is empty, it means that the next hook function is executed directly. If the parameter is path, the corresponding route is navigated; if the parameter is false, the jump is forbidden; if the parameter is error, the navigation finally passes the wrong listener function.
  2. Intra-route navigation hooks, defined in route configuration, that are owned by individual routes.
  3. BeforeRouteUpdate, beforeRouteEnter, beforeRouteLeave.

151. What is the difference between route and router?

Route is a route information object, including the path, params, name, hash, and Query information of the route

Router is a route instance object, including path jump method, hook function, etc.

152. What modifiers do you use for vue?

The common modifiers of vue are. Pevent,.stop,.self, etc.. Pevent means to cancel the default behavior of the event, such as the a tag to cancel the jump default behavior,.stop means to cancel the bubbling event, and.self means that the event occurred in the element itself rather than its child.

153. What is the function of the key value in vue?

Key values in vUE can be called in two cases:

  1. V – if used in the key value, because the vue in order to better and more fast rendering page default to reuse principle, as far as possible reuse existing elements rather than from scratch, for example, an input element in our update switch will reuse the same element, then the user input before the content may be preserved it is not in conformity with the specification, Therefore, add a key attribute to each V-if as a unique identifier so that elements using the key are not reused.
  2. The key value is used in V-for because we use V-for to update iterated rendered elements. In order to avoid vUE’s default principle of in-place reuse, we add the key value with a unique identifier. When updating the render, if the data list changes, VUE does not move DOM elements to change the location, but reuses the original elements. So add a key value to each list item to track the identity of each element.
  3. Provides a unique identifier for the diff algorithm of the virtual DOM

154. Is computed different from Watch?

Look at 149 points

155. What is the function of the keep-alive component?

If we need to save the state of some components during component switching, we can use the keep-alive component to wrap the components that need to save the state, preventing multiple renders.

156. What is the difference between mixins and mixins in vue?

Mixins are global mixins, which means that creating a global mixin component affects all instances of vUE component creation.

Mixins provide a flexible way to distribute reusable functionality in VUE components, where a mixin object can be mixed with any component content. When a component uses mixobject, all mixobject options are “blended” into all options within the component. When components and mixins have the same options, appropriate merging is performed, for example, data objects are internally recursively merged, and component data takes precedence in times of conflict. The hook function mixed with the object is called before the hook function inside the component. Some options, such as methods and components, are combined into one object. If the key names of two objects conflict, the key-value pair of the component object is taken.

157. How many Content-Types are commonly used in development?

  1. Application/X-www-form-urlencoded: This data format is mainly stored in the body, mainly key1=val1&key2=val2 format (key-value pair) encoding.
  2. Application/JSON: This data format is mainly encoded in JSON string format.
  3. Text/XML: This method is used to submit data in XML format.
  4. Multipart /form-data: this data format is used to submit data in form form.

158. How to encapsulate a javascript type determination function?

function typeof(value){
    if(value === null) {return null + ' ';
    }
    if(typeof value === 'object') {// If it is a reference data type
        let valueClass = Object.prototype.toString.call(value).split(' ') [1],
            type = valueClass.split(' ');
        type.pop();
        return type.join(' ').toLowerCase();
    } else {
        returnvalue; }}Copy the code

159. How do I tell if an object is empty?

  1. Use for.. In:

    For (var k in obj){// Return true if the object is not empty; } return false;Copy the code
  2. Convert to JSON string using the stringify method that comes with JSON

    if(JSON.stringify(obj) === '{}'){
        return false;
    }
    return true;
    Copy the code
  3. The new object.keys () method in ES6 returns data consisting of all the enumerable properties of an Object

    var a = {}; Object.keys(a); If (object.keys (obj).length === 0){return false; } return true;Copy the code

160. Use closures to print 1,2,3,4 every second

for(let i = 1; i <= 4; i++){
    setTimeout(function(){
        console.log(i)
    }, i*1000)}for(var i = 1; i <=4; i++){
    (function(j){
        setTimeout(function(){
            console.log(j)
        }, j*1000)
    })(i)
}
Copy the code

161. Write a JSONP by hand

function jsonp(url, params, callback){
    // Does the url itself have an argument?
    queryString = url.indexOf('? ') = = ='1' ? '? ' : '&';
    for(var k in params){
        if(params.hanOwnProperty(k)){
            queryString += k + '='+ params[k]; }}// Define a random function name to add to the argument
    var randomName = Math.random().toString().replace('. '.' ');
    var myFunction = 'myFunction' + randomName;
    queryString += 'callback' + '=' + myFunction;
    url += queryString;
    // Dynamically create script tags
    var myScript = document.createElement('script');
    myScript.src = url;
    window[myFunction] = function(){ callback(... arguments);// Delete the dynamic script
        doucment.getElementsByTagName('head') [0].removeChild(myScript);
    };
    // Insert the script into the head
    document.getElementsByTagName('head') [0].appendChild(myScript);
  
Copy the code

162. Write an observer mode by hand?

var event = (function(){
    var topics = {};
    return {
        // Publish mode
        publish: function(topic, info){
            console.log('publish a topic:' + topic);
            if(topics.hasOwnProperty(topic)){
                topics[topic].forEach(function(handler){ handler(info ? info : {}); })}},// Subscription mode
        subscribe: function(topic, handler){
            console.log('subscribe a topic:' + topic);
            if(! topics.hasOwnProperty(topic)){ topics[topic] = []; } topics[topic].push(handler); },remove: function(topic, handler){
            if(! topics.hasOwnProperty(topic)){return;
            }
            var topicIndex = -1;
            topics[topic].forEach(function(element, index){
                if(element === handler){
                    topicIndex = index;
                }
            })
            topics[topic].splice(topicIndex, 1);
        },
        removeAll: function(topic){
            console.log('remove all the handler on the topic');
            if(topics.hasOwnProperty(topic)){
                topics[topic].length = 0; }}}}) ()var handler = function(info){
    console.log(info);
}
// Subscribe to the Hello theme
event.subscribe('hello', handler);
// Publish the Hello theme
event.publish('hello'.'hello world');

Copy the code

163. The EventEmitter implementation

class eventEmitter {
    constructor(){
        this.events = {}
    }
    on(event, callback){
        let callbacks = this.events[event] || [];
        callbacks.push(callback);
        this.events[event] = callbacks;
        return this;
    }
    emit(event, ... args){
        let callbacks = this.events[event];
        callbacks.forEach(fn= >{ fn(... args); })return this;
    }
    off(event, callback){
        let callbacks = this.events[event];
        callbacks = callbacks.filter(fn= > returnfn ! == callback);this.events[event] = callbacks;
        return this;
    }
    once(event, callback){
        let wrapFun = function(. args){ callback(... args);this.off(wrapFun);
        }
        this.on(event, wrapFun);
        return this; }}Copy the code

164. An often overlooked front-end JS interview question

function Foo() {
  getName = function() {
    alert(1);
  };
  return this;
}
Foo.getName = function() {
  alert(2);
};
Foo.prototype.getName = function() {
  alert(3);
};
var getName = function() {
  alert(4);
};
function getName() {
  alert(5);
}

// Write the following output:
Foo.getName(); / / 2
getName(); / / 4
Foo().getName(); / / 1
getName(); / / 1
new Foo.getName(); / / 2
new Foo().getName(); / / 3
new new Foo().getName(); / / 3

Copy the code

165. How do I determine page availability times and what is the Performance API?

In order to solve the problem that the browser’s time accuracy is not small enough to be accurate to the millisecond level and the server cannot be informed of the resource request event, JavaScript added a performance API, which is a precision timestamp. It represents the time stamp when the previous web page closed, and the other is the loadEventEnd, which is the high-precision time stamp at the end of the load event return function execution for the current web page. Use these two attributes to calculate the total loading time of the page:

var t = performance.timing;
var pageLoadTime = t.loadEventEnd - t.navigationStart;
Copy the code

166. naming rules in js

Variables are usually named with the first character being a letter, underscore, or dollar following $. Other characters can be letters, numbers, underscores, and dollar signs. Naming conventions typically require a camel name, which can be consistent with ECMAScript’s built-in functions and object configurations.

Can the semicolon at the end of the js statement be omitted?

It is best not to omit it, because adding semicolons to the end of statements does not generate errors after code compression is optimized, and facilitates future maintenance

168. Object.assign()

It copies all enumerable properties from one or more source objects to another target object and returns the target object, a shallow copy.

169. Math. Ceil and Math. The floor

Math.ceil() rounds up the floating point value, math.floor () rounds down the floating point value.

170.js for loop note points

for (var i = 0, j = 0; i < 5, j < 9; i++, j++) {
  console.log(i, j);
}
Copy the code

If multiple statements are identified, the last statement prevails. In the preceding code, j < 9 prevails. If the statement is null, the loop continues.

171. What about a list with, say, 100,000 entries?

When we have a large amount of data, we need to consider several issues: first, whether the data needs to be displayed synchronously, and second, whether the data needs to be displayed sequentially

Solutions:

  1. We can use paging technology to make these data displayed in pages on the browser, only one page of data is displayed and loaded at a time, and the rest of the data is rendered to the server when the browser operates on different pages.
  2. Using lazy loading, where some data is displayed first and then loaded when the browser needs to display some data, reduces server-side stress and optimizes performance.
  3. Data can be grouped to display, such as display a timer, a certain period of time to display part of the data.
  4. The use of virtual list, reduce the pressure of page DOM element construction, greatly improve the efficiency of browser rendering

172. Js countdown correction implementation?

Juejin. Cn/post / 684490…

173. The mode of interprocess communication?

Pipeline communication, task queue communication, semaphore communication, signal communication, socket communication, shared memory communication.

174. How to find the most frequently used words in an English passage?

function findWord(article){   
  if(article == null) {return article  
  }   
  article = article.trim().toLowerCase();   
  var wordList = article.match(/[a-z]+/g);   
  article = ' ' + wordList.join(' ') + ' ';   
  var max = 0;   
  var maxWord = ' ';   
  var list = [];   
  wordList.forEach(word= > {   
    if(list.indexof(word) === '1'){   
      list.push(word);   
      var newWord = new RegExp(' ' + word + ' ');    
      var wordLength = article.match(newWord).length;   
      if(wordLength > max){ max = wordLength; maxWord = word; }}})return maxWord + ' ' + max;  
}

Copy the code

After the speech

Because the word limit can only be divided into up and down! JS based on the previous chapter

In this must be referred to the reference article – cattle passenger network god