174 JavaScript Interview Tips (Part 2)
Vue Chinese community yesterday, the article has a lot of gold code to read recommended suggestions and favorites
Source |Github.com/CavsZhouyou…
The whole article is long to ensure reading experience, so it is divided into three parts
174 JavaScript Interview Tips (Part 1)
174 JavaScript Interview Tips
The following is part three
121. What is the difference between A URL and a URI?
Uris: Uniform Resource Identifiers URIs: Uniform Resource Locations URIs: Uniform Resource Identifiers URIs: Uniform Resource Identifiers URIs: Uniform Resource Identifiers URIs: Uniform Resource Identifiers URIs: Uniform Resource Identifiers URIs: Uniform Resource Identifiers URIs: A Universal Resource Name is a Universal Resource identifier (URI) that identifies a Resource with a unique identifier. It is an abstract definition. That is, no matter what method is used to define a Resource, a URI can be called as long as it uniquely identifies a Resource. The URL refers to the Uniform resource locator and the URN refers to the uniform resource name. Urls and UrNs are subsets of URIs, which can be understood as identifying a resource using an address, and UrNs, which can be understood as identifying a resource using a name.Copy the code
For more information, see “What’s the Difference between A URI and a URL in HTTP?” Do you know the difference between a URL, a URI, and a URN? The Difference between URIs, urls, and UrNs
122. Cache differences between GET and POST requests
Related knowledge:
Get requests are similar to lookups in that the user retrieves data without having to connect to the database every time, so caching can be used. Unlike Post, which generally does modification and deletion, it must interact with the database, so it cannot use caching. Therefore, GET requests are suitable for request caching.Copy the code
Answer:
Caching is generally only applicable to requests that do not update server data. Generally, GET requests are search requests and do not modify server resource data, whereas POST requests generally modify server data. Therefore, GET requests are generally cached, but POST requests are rarely cached.Copy the code
For more information, please refer to “HTML: Understanding the Difference between POST and GET and Caching issues”.
123. Lazy loading and preloading of images
Related knowledge:
Preloading: Images are loaded ahead of time and rendered directly from the local cache when the user needs to view them. Lazy loading: The main purpose of lazy loading is to serve as a front-end optimization for the server, reducing the number of requests or delayed requests. The essence of two technologies: the behavior of both is opposite, one is early loading, one is slow or even not loading. Lazy loading relieves the pressure on the front end of the server, while preloading increases it.Copy the code
Answer:
Lazy loading, also known as lazy loading, refers to the delay of loading images in long web pages, and then loading them when users need to visit. In this way, the loading speed of the first screen of a website can be improved, the user experience can be improved, and the pressure on the server can be reduced. It is suitable for e-commerce sites with lots of images and long pages. Lazy loading is the implementation of the principle, the pictures on the page of the SRC attribute is set to an empty string, the image of the real path stored in a custom attribute, when the page scroll, judge, if the image into the page visual area, the real path out of the custom attributes assigned to the SRC attribute of the images, In this way, the picture can be loaded lazily. Preloading is the process of requesting the required resources to be loaded locally in advance so that they can be accessed directly from the cache later when they are needed. Preloading can reduce user waiting time and improve user experience. The most common way of preloading that I know is to use image object in JS. SCR attribute is set for image object to realize preloading of image. Both of these methods are ways to improve the performance of the web page, the main difference between the two is that one is loaded in advance, one is slow or even not loaded. Lazy loading relieves the pressure on the front end of the server, while preloading increases it.Copy the code
For details, please refer to: lazy loading and preloading, Webpage image loading Optimization scheme, image and other resources preloading based on user behavior.
124. What is the difference between mouseover and MouseEnter?
The mouseEnter event is triggered when the mouse moves over the element, similar to mouseover, except that the mouseEnter does not bubble. Because mouseEnter does not support event bubbling, the mouseover and Mouseout events are triggered when entering or leaving an element's child elements, but the MouseEnter and Mouseleave events are not.Copy the code
For details, see: Why MouseEnter and MouseOver Are So Intertwined.
125. js drag function implementation
Related knowledge:
The first three events are mousedown, Mousemove, and mouseup. When the mouse is clicked and pressed, you need a tag to indicate that the mouse has been pressed, and you can execute the specific method in mousemove. ClientX, clientY refers to the coordinates of the mouse, marking abscis and ordinate respectively, and we use offsetX and offsetY to represent the initial coordinates of the element. The example of movement should be: the coordinates when the mouse moves - the coordinates when the mouse is down. That is, the positioning information is: the coordinate when the mouse is moved - the coordinate when the mouse is down + the element's initial offetLeft.Copy the code
Answer:
The dragging process of an element can be divided into three steps. The first step is to press down the target element with the mouse; the second step is to move the mouse in the state of pressing the mouse; the third step is to lift the mouse and the dragging process ends. These three steps correspond to three events, the Mousedown event, the Mousemove event and the Mouseup event. Drag events are performed only when the mouse is moved in the down state, so we need to set a state in the mousedown event to indicate that the mouse is down, and then cancel that state in the Mouseup event. The first thing we need to do in a mousedown event is determine if the target element is a drag element. If it is a drag element, we set the state and save the position of the mouse at that time. Then, in the Mousemove event, we determine the coordinates of the drag elements in motion by judging the relative movement of the current and previous mouse positions. Finally, after the mouseup event is triggered, the state is cleared and the drag event ends.Copy the code
For more information, please refer to “Basic Ideas of implementing drag and drop function with Native JS”.
126. Why use setTimeout to implement setInterval? How do you simulate it?
Related knowledge:
Function mySetInterval(fn, timeout) {function mySetInterval(fn, timeout) { Var timer = {flag: true}; // Set the recursive function to simulate timer execution. function interval() { if (timer.flag) { fn(); setTimeout(interval, timeout); } // Start the timer setTimeout(interval, timeout); // Return timer; }Copy the code
Answer:
SetInterval is used to execute a function at a specified interval, but it is not executed immediately. It is used to queue events at intervals, and only when the current stack is empty can it be removed from the event queue. Therefore, it may occur that the current execution stack is executed for a long time, resulting in the accumulation of multiple timer events in the event queue. When the execution stack ends, these events will be executed in sequence, so that the effect of the execution of a period of time cannot be achieved. To address this shortcoming of setInterval, we can use a recursive call to setTimeout to simulate setInterval, so that we ensure that only one event ends before we fire the next timer event, which solves the setInterval problem.Copy the code
For more information, see: Implementing setInterval with setTimeout. What are the disadvantages of setInterval?
127. What should be noticed about let and const?
- 1. Declared variables are valid only in the block of code in which they are declared
- 2. There is no declaration promotion
- 3. Temporary dead zone exists. If used before variable declaration, an error will be reported
- 4. Do not allow repeated statements. Repeated statements may cause errors
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?
A tail-call is when the last step of a function calls another function. Our code execution is stack based, so when we call another function in one function, we keep the current execution context and then add another execution context to the stack. With tail-call optimization, we can save memory by not having to keep the current execution context because it is already the last step of the function. But ES6 tail-call optimization is only enabled in strict mode, not normal mode.Copy the code
130. What is the Symbol type?
- 1. Do not use the new command before the Symbol function, otherwise an error will be reported.
- 2. The Symbol function can accept a string as an argument representing a description of the Symbol instance, mainly for display on the console or for easy differentiation when converted to a string.
- 3.Symbol is the attribute name. This attribute does not appear in for… In, for… Of loop, will not be the Object. The keys (), Object, getOwnPropertyNames (), JSON. The stringify () returns.
- 4. Object. GetOwnPropertySymbols method returns an array of all members is the current Object is used as the Symbol value of the property name.
- 5.Symbol.for takes a string as an argument and searches for a Symbol value named with that argument. If so, return the Symbol, otherwise create and return a Symbol with the name of the string.
- The Symbol. KeyFor method returns the key of a registered Symbol type value.
131. Set and WeakSet structures?
- 1.ES6 provides a new data structure, Set. It is similar to an array, but the values of the members are unique and there are no duplicate values.
- 2.WeakSet structure is similar to Set, which is also a collection of non-repeating values. However, WeakSet members can only be objects, not other types of values. WeakSet objects are weak references, that is, garbage collection mechanism does not consider WeakSet’s reference to the object.
132. Map and WeakMap structure?
- 1.Map data structure. It is a collection of key-value pairs similar to objects, but the range of “keys” is not limited to strings. Values of all types (including objects) can be used as keys.
- 2.WeakMap structure is similar to Map structure and is also used to generate a set of key-value pairs. However, WeakMap only accepts objects as key names (except null) and does not accept other types of values as key names. Moreover, the object to which the key name of WeakMap points is not included in the garbage collection mechanism.
133. What is Proxy?
Proxy is used to modify the default behavior of some operations, which is equivalent to making changes at the language level. Therefore, it is a kind of "metaprogramming", that is, programming a programming language. Proxy can be understood as a layer of "interception" before the target object. All external access to the object must pass this layer of interception. Therefore, Proxy provides a mechanism for filtering and rewriting external access. The word Proxy is used to mean that it acts as a Proxy for certain operations.Copy the code
134. Reflect object creation purpose?
- 1. Place Object methods that are clearly internal to the language (such as Object.defineProperty) on Reflect.
- 2. Modify the return results of some Object methods to make them more reasonable.
- 3. Make Object operations functions.
- 4.Reflect’s method corresponds to Proxy’s method. As long as it is a Proxy’s method, you can find the corresponding method on Reflect’s object. This allows the Proxy object to easily call the corresponding Reflect method, completing the default behavior as a basis for modifying the behavior. That is, no matter how the Proxy changes the default behavior, you can always get the default behavior in Reflect.
135. Lookup methods introduced by the require module?
When Node encounters require(X), it does so in the following order. (1) If X is a built-in module (e.g. Require (' HTTP ')) a. Returns the module. B. No further action is required. (2) If X begins with "./" or "/" or ".. /" a. Determine the absolute path of X based on the parent module of X. B. Regard X as a file and search for the following files. If one of the following files exists, the file is returned and the execution is not continued. Xx.js, son, and ode c. Use X as a directory and search for the following files one by one. If one of the following files exists, the system returns the file, and no further operation is performed. X/package.json X/index.js X/index.json X/index.node (3) If X does not contain a path a. Determine the possible installation directory of X based on the parent module of X. B. In each directory, load X as a file name or directory name. (4) Throw "Not found"Copy the code
For more information, please refer to: Require () source code interpretation.
136. What are Promises/A+ Promises?
Promise objects are a solution to asynchronous programming and were first proposed by the community. Promises/A+ the Promises/A+ specification is the JavaScript Promise standard. Promises define the features that A Promise must have. Promise is a constructor that takes a function as an argument and returns a Promise instance. A Promise instance has three states, pending, Resolved, and Rejected, representing ongoing, successful, and failed, respectively. The instance state can only be changed from "Resolved" or "Rejected" to "Pending". Once the instance state is changed, it is frozen and cannot be changed. State changes are done through the resolve() and reject() functions, which can be called after an asynchronous operation to change the state of a Promise instance, whose prototype defines a then method, The then method is used to register callback functions for two state changes. This callback is a microtask and is executed at the end of the current event loop.Copy the code
For more information, please refer to: Promises/A+ Specifications, Promise
Write a Promise by hand
const PENDING = "pending"; const RESOLVED = "resolved"; const REJECTED = "rejected"; Function MyPromise(fn) {var self = this; This. state = PENDING; This. value = null; // This. ResolvedCallbacks = []; // This. ResolvedCallbacks = []; This. RejectedCallbacks = []; Resolve (value) {resolve(value) { If (value instanceof MyPromise) {return value. Then (resolve, reject); SetTimeout (() => {// Can only be changed if the state is pending, If (self. State === PENDING) {self. State = RESOLVED; // Set the value self.value = value; / / implement the callback function self. ResolvedCallbacks. ForEach (callback = > {callback (value); }); }}, 0); SetTimeout (() => {// Only if the state is pending can change if (self.state === PENDING) {// Modify state self.state = REJECTED; // Set the value self.value = value; / / implement the callback function self. RejectedCallbacks. ForEach (callback = > {callback (value); }); }}, 0); } // pass both methods into the function try {fn(resolve, reject); } catch (e) {reject(e) {reject(e); }} mypromise.prototype. Then = function(onResolved, onRejected) { Because these 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, then add the function corresponding to the list if (this. State = = = PENDING) {this. ResolvedCallbacks. Push (onResolved); this.rejectedCallbacks.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?
Use JS to set the font of the DOM to a value, and then take it out. If the value is set successfully, it indicates support.Copy the code
139. How to make JS code Error statistics?
Error Statistics for window.error events using the browser.Copy the code
140. Singleton Pattern What is a pattern?
The singleton pattern ensures that globally only one instance can be accessed. For example, the implementation of commonly used components such as popbox and global state implementation.Copy the code
141. What is the strategic pattern?
Policy mode is mainly used to separate the method implementation from the method invocation, external through different parameters can call different policies. I mainly use it to separate method definitions and method calls at the view layer when the MVP pattern is decoupled.Copy the code
142. What is the proxy mode?
The proxy pattern provides a proxy or placeholder for an object to control access to it. For example, the common event broker.Copy the code
143. What is the mediator model?
The mediator pattern means that multiple objects communicate through a mediator rather than directly, which decouples the objects that communicate.Copy the code
144. What is the adapter mode?
The adapter is used to resolve the incompatibility of two interfaces by wrapping the two interfaces in a layer without changing the existing interface. The adapter pattern can be used if we need a new way to return an interface, but the old interface is already used in too many places to be changed. For example, if we need a custom time return format, but we cannot modify the JS time formatting interface, we can use the adapter pattern.Copy the code
For more information on design patterns, see: Tips for Front-end Interviewing, JavaScript Design Patterns, and Common Design Patterns in JavaScript.
145. What is the difference between the Observer model and the publish-subscribe model?
The publish-subscribe model is actually the observer model in a broad sense where the observer needs to subscribe directly to the target event. After the target issues an event that changes the content, the event is received directly and the response is made. In the publish-subscribe model, there is an additional scheduling center between publisher and subscriber. The dispatch center receives events from publishers on the one hand and publishes them to subscribers, who need to subscribe to events in the dispatch center. The relationship between publisher and subscriber is decoupled through the scheduling center. Using the published subscriber model is better for the maintainability of our code.Copy the code
For more information, see: What’s the difference between the Observer model and the Publish/subscribe Model?
146. What is the life cycle of Vue?
The lifecycle of a Vue refers to the sequence of processes from component creation to destruction, known as the lifecycle of a Vue. By providing hook functions for each phase of the Vue lifecycle, we can implement some operations in each phase of the Vue lifecycle.Copy the code
147. What are the life stages of Vue?
Vue has eight life stages: before, after, load, load, update, update, destroy, and destroy, each of which corresponds to a lifecycle hook function. (1) beforeCreate hook function, after instance initialization, before data listening and event configuration. So we don't get data in this event. (2) Created hook function, which is triggered when the instance is created and can access properties such as data and methods. However, the component is not yet mounted to the page, so the $EL property is not accessible at this time. This function usually does some page initialization, such as making an Ajax request for data to initialize the page. BeforeMount hook function, triggered before component is mounted to the page. Before beforeMount, the corresponding template is found and compiled into the render function. The mounted hook function is triggered after the component is mounted to the page. At this point, DOM elements in the page can be retrieved through the DOM API. BeforeUpdate hook functions are triggered during reactive data updates, before the virtual DOM is re-rendered and patched, at which time we can do some actions on elements that may be removed, such as removing event listeners. Updated hook function, invoked after virtual DOM is re-rendered and patched. BeforeDestroy hook function, called before instance destruction. In this step we can destroy timers, unbind global events, and so on. Everything in the Vue instance is unbound, all event listeners are removed, and all subinstances are destroyed after the instance is destroyed. When we use keep-alive, there are also two hook functions, activated and deactivated. Components wrapped with keep-alive are not destroyed during switching, but cached in memory and executed by deactivated hook function. After hitting the cache rendering, the actived hook function is executed.Copy the code
For details, please refer to vUE Life Cycle In Depth and VUE Examples.
148. How are parameters passed between Vue components?
(1) The first method of communication between parent and child components is that the child component accepts the data of the parent component through the props property. Then the parent component registers the listening event on the child component, and the child component sends data to the parent component through the emit triggering event. The second is to give the child component a name through the ref attribute. The parent gets the child component by $refs component name, and the child gets the parent component by $parent, which also communicates. The third way is to use Provider /inject. Provider provides variables in the parent component and inject variables in the child component. No matter how deep the child component is, as long as inject is invoked, the data in the provider can be injected. (2) The first method of communication between sibling components is to use eventBus. Its essence is to create an empty Vue instance as the object of message transmission. The communication component introduces this instance, and the communication component realizes message transmission by listening and triggering events on this instance. The second way is to get sibling components via $parent.$refs, which can also communicate. (3) Using eventBus between any components creates an event hub, a sort of hub, that can be used to transmit and receive events. If the business logic is complex and many components need to process some common data at the same time, these methods may not be conducive to the maintenance of the project. In this case, vuex can be used. The idea of VUEX is to isolate the common data and manage it as a global variable so that other components can read and write the common data, thus achieving decoupling.Copy the code
For more information, please refer to the Complete Data Transfer between VUE Components.
149. Differences between computed and Watch?
(1) Computed is to calculate a new attribute and mount it to the Vue instance, while watch monitors the data that already exists and is mounted to the Vue instance, so watch can also monitor changes in computed attributes. (2) Computed by nature is a lazy observer with caching properties, and only when the dependency changes and the first access to computed properties, new values are computed. Watch, on the other hand, calls the execution function when the data changes. (3) In terms of usage scenarios, computed applies to one data affected by multiple data, while Watch applies to one data affecting multiple data.Copy the code
For more information, please refer to “Tumbler doing Interview: On the Implementation Principle of Computed Tomography in Vue” and “In-depth Understanding of the Implementation Principle and Implementation Method of Vue watch”.
150. Navigation hook functions in vue-Router
(1) Global hook functions beforeEach and afterEachbeforeEach have three arguments, to represents the route object to enter and from represents the route object to leave. Next is a mandatory function. If no arguments are passed, the next hook function is executed, terminating the jump if false, navigating to the corresponding route if a path is passed, and terminating navigation if error is passed, which passes an error listener. (2) Exclusive hook function for single routes. BeforeEnter is defined directly on route configuration. (3) There are three kinds of navigation hooks in the component: beforeRouteEnter, beforeRouteUpdate and beforeRouteLeave. They are defined directly within the routing component.Copy the code
For more information, see: Navigation Guard
151. What is the difference between router and router?
$route is the "routing information object", including path, Params, Hash, Query, fullPath, matched, name and other routing information parameters. $router is a "router instance" object that includes hop methods, hook functions, etc.Copy the code
152. What modifiers do you use for vue?
.prevent: Submit events that no longer reload the page; . Stop: prevents the click event from bubbling. .self: Fires when an event occurs in the element itself rather than a child element;Copy the code
153. What is the function of the key value in vue?
The role of a key value in a VUE can be considered in two cases. The first case is when key is used in v-if. Since Vue renders elements as efficiently as possible, it is common to reuse existing elements rather than rendering them from scratch. So when we switch elements using V-if, if there is an element of the same type before and after the switch, the element will be reused. If it is the same input element, the user's input will not be cleared before and after the switch, which is not desirable. Therefore, we can uniquely identify an element by using a key, in which case the element with the key will not be reused. The key is used to identify an individual element. The second case is when keys are used in v-for. When v-for is used to update a list of rendered elements, it defaults to a "reuse in place" strategy. If the order of data items changes, Vue does not move DOM elements to match the order of data items, but simply reuses each element there. Therefore, by providing a key value for each list item, Vue can track the identity of the element for efficient reuse. The key is used to efficiently update and render the virtual DOM.Copy the code
Vue2.0 V-for: What is the key used for? The role of Key in VUE
154. Is computed different from Watch?
Computed is a property that relies on other properties to compute values, and computed values are cached and returned only when computed values change. Watch listens for a change in the value and executes a callback, in which logical operations can be performed.Copy the code
155. What is the function of the keep-alive component?
If you need to save the state of some components to prevent multiple renders when switching between components, you can wrap the components that need to be saved with the keep-alive component.Copy the code
156. What is the difference between mixins and mixins in vue?
Mixins are used for global mixing and affect each component instance. Mixins are probably the most common way to extend components. If multiple components have the same business logic, it can be stripped out and mixed into code through mixins, such as pull-up and pull-down data loading logic. It is also important to note that mixins incorporate hook functions that are executed before the component's own hook functions, and are selectively merged when they encounter options with the same nameCopy the code
For more information, please refer to “The Way of Front-end Interview” and “Interfuse”
157. How many Content-Types are commonly used in development?
(1) Application/X-www-form-urlencoded native form form of browser. If encType attribute is not set, data will be submitted in Application/X-www-form-urlencoded. The data submitted in this way is stored in the body, and the data is encoded according to key1=val1&key2=val2. The KEY and val are URL transcoded. (2) Multipart /form-data is also a common POST submission method. It is usually used for uploading files in forms. Application/JSON tells the server that the body of the message is a serialized JSON string. (4) Text/XML is mainly used to submit data in XML format.Copy the code
For more information, see: Common Content-Types
158. How to encapsulate a javascript type determination function?
Function getType(value) {if (value === null) {return value + ""; } / / judge the data as a reference type if typeof (value = = = "object") {let valueClass = object. The prototype. The toString. Call (value), type = valueClass.split(" ")[1].split(""); type.pop(); return type.join("").toLowerCase(); Return typeof value;} else {return typeof value; }}Copy the code
For more information, please refer to “JavaScript Topic Type Judgment (PART 1)”.
159. How do I tell if an object is empty?
function checkNullObj(obj) { return Object.keys(obj).length === 0; }Copy the code
For more information, please refer to js to determine whether an object is null.
160. Use closures to print 1,2,3,4 every second
For (var I = 0; i < 5; i++) { (function(i) { setTimeout(function() { console.log(i); }, i * 1000); })(i); }// Use let block-level scope for (let I = 0; i < 5; i++) { setTimeout(function() { console.log(i); }, i * 1000); }Copy the code
161. Write a JSONP by hand
Function jsonp(url, params, callback) {let queryString = url.indexof ("?" ) = = = "1"? "?" : "&"; For (var k in params) {if (params.hasownProperty (k)) {queryString += k + "=" + params[k] + "&"; }} let random = math.random ().toString().replace(".", ""), callbackName = "myJsonp" + random; QueryString += "callback=" + callbackName; // build request let scriptNode = document.createElement("script"); scriptNode.src = url + queryString; Window [callbackName] = function() {// Call callback(... arguments); / / remove this introduction script document. GetElementsByTagName (" head ") [0]. RemoveChild (scriptNode); }; / / a request document. GetElementsByTagName (" head ") [0]. The appendChild (scriptNode); }Copy the code
For more information, please refer to “Native JSONP Implementation” and “JSONP Principles and Implementation”.
162. Write an observer mode by hand?
var events = (function() { var topics = {}; Return {subscribe: function(topic, handler) {if (! topics.hasOwnProperty(topic)) { topics[topic] = []; } topics[topic].push(handler); }, // Publish the event, which triggers the observer to call the event publish: function(topic, info) { if (topics.hasOwnProperty(topic)) { topics[topic].forEach(function(handler) { handler(info); }); Remove: function(topic, handler) {if (! topics.hasOwnProperty(topic)) return; var handlerIndex = -1; topics[topic].forEach(function(item, index) { if (item === handler) { handlerIndex = index; }}); if (handlerIndex >= 0) { topics[topic].splice(handlerIndex, 1); RemoveAll: function(topic) {if (topics. HasOwnProperty (topic)) {topics[topic] = []; }}}; }) ();Copy the code
For details, please refer to JS Event Model.
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; } off(event, callback) { let callbacks = this.events[event]; this.events[event] = callbacks && callbacks.filter(fn => fn ! == callback); return this; } emit(event, ... args) { let callbacks = this.events[event]; callbacks.forEach(fn => { fn(... args); }); return this; } once(event, callback) { let wrapFun = function(... args) { callback(... args); this.off(event, 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 (); // 2getName(); // 4Foo().getName(); // 1getName(); // 1new Foo.getName(); // 2new Foo().getName(); // 3new new Foo().getName(); / / 3Copy the code
For more information, see: “A JavaScript Interview Question often Overlooked by Front-end Programmers”, “A JavaScript Interview Question examining the Precedence of operators”, and “an Often Overlooked Front-end JS Interview Question”.
165. How do I determine page availability times and what is the Performance API?
The Performance API is used to precisely measure, control, and enhance browser Performance. This API provides a level of accuracy for measuring web site performance that was never possible before. The downside of using getTime to calculate script time is that, for one thing, the getTime method (and the other methods on Date objects) are accurate to the millisecond level (thousandths of a second), making it impossible to get much smaller time differences. Second, it only captures the progress of the code as it runs, not the progress of some background events, such as how long it took the browser to load a web page from the server. To address these two shortcomings, ECMAScript 5 introduces the "High Precision timestamp" API, which is deployed on Performance objects. It is accurate to one thousandth of a millisecond (one millionth of a second). NavigationStart: Unix millisecond timestamp when the previous page of the current browser window closes and an Unload event occurs. If there is no previous web page, it equals the fetchStart property. LoadEventEnd: Returns the Unix millisecond timestamp at the end of the run of the callback function for the load event of the current page. If the event has not already occurred, return 0.Copy the code
Based on these attributes, you can calculate the time taken for each stage of web page loading. For example, the time taken to load a web page is calculated as follows:
var t = performance.timing; var pageLoadTime = t.loadEventEnd - t.navigationStart;Copy the code
For more information, see: Performance API
166. naming rules in js
(1) the first character must be letters, underscores (_), or a dollar sign ($) (2) the rest of the characters can be underlined, the dollar sign, or any letters or Numbers characters generally we recommend hump method, named variable name for the built-in function, and because it can with ECMAScript object consistent naming format.Copy the code
See ECMAScript Variables for more information.
Can the semicolon at the end of the js statement be omitted?
In the ECMAScript specification, a semicolon at the end of a statement is not required. However, it is generally best not to omit the semicolon, because adding a semicolon on the one hand makes our code more maintainable, and on the other hand prevents errors when we compress our code.Copy the code
168. Object.assign()
The object.assign () method is used to copy the values of all enumerable properties from one or more source objects to target objects. It will return the target object.Copy the code
169. Math. Ceil and Math. The floor
Math.ceil() === round up, and the function returns a minimum integer greater than or equal to the given number. Math.floor() === round down, the function returns a maximum integer less than or equal to the given number.Copy the code
170.js for loop note points
for (var i = 0, j = 0; i < 5, j < 9; i++, j++) { console.log(i, j); }// When a statement contains more than one statement, the value of the last statement is used, so the above code is executed 10 times. // If the statement is null, the loop will continue.Copy the code
171. What about a list with, say, 100,000 entries?
Questions to consider: Does this processing have to be done synchronously? Does the data have to be done in order? Solution :(1) data paging, using the principle of paging, each time the server only returns a certain number of data, the browser each time only part of the load. (2) Use lazy loading method, load part of the data at a time, and load the rest of the data when needed. (3) The use of array block technology, the basic idea is to create a queue for the items to be processed, and then set the timer every time after a period of time to take out a part of the data, and then use the timer to take out the next item to be processed, and then set another timer.Copy the code
172. Js countdown correction implementation?
In the front-end implementation, we usually use setTimeout and setInterval methods to achieve a countdown effect. However, there will be time deviation when using these methods, which is caused by the program execution mechanism of JS. The function of setTimeout and setInterval is to add the callback event to the event queue at intervals, so the event is not executed immediately. It waits until the current stack is empty before fetching the event execution, so the time the event waits for execution is the cause of the error. Generally, there are two ways to solve the error in the countdown :(1) the first way is to calibrate the countdown time by sending a request to the server through the front end timing to obtain the latest time difference. (2) The second method is realized by the way that the front end automatically adjusts the interval time according to the deviation time. This method first realizes the countdown in the recursive way of setTimeout, and then records the number of seconds that have been counted through a variable. Each time the function is called, we increment the variable by one. Then, based on the variable and the interval time, we can calculate the time that should be displayed without bias. Then subtract the current real time from this time, so that we can get the time deviation, so when we set the interval size of the next timer, we will subtract this deviation from the interval time, in order to realize the correction of the time error caused by the program execution.Copy the code
For more information, please refer to “JavaScript Front-end Countdown Correction Implementation”.
173. The mode of interprocess communication?
- 1. Pipeline communication
- 2. Message queue communication
- 3. Semaphore communication
- 4. Signal communication
- 5. Shared memory communication
- 6. Socket communication
For more information, please refer to “8 Ways of Communication between processes” and “A Simple Explanation of Processes and Threads”.
174. How to find the most frequently used words in an English passage?
Function findMostWord(article) {if (! article) return; Article = article.trim().tolowerCase (); let wordList = article.match(/[a-z]+/g), visited = [], maxNum = 0, maxWord = ""; article = " " + wordList.join(" ") + " "; ForEach (function(item) {if (visited. IndexOf (item) < 0) {// Join visited visited. Push (item); let word = new RegExp(" " + item + " ", "g"), num = article.match(word).length; if (num > maxNum) { maxNum = num; maxWord = item; }}}); return maxWord + " " + maxNum; }Copy the code
Interview question warehouse recommended:
- Github.com/febobo/web-…
** Recommended reading: ** * [174 lines of JavaScript Interview knowledge summary (on)] (HTTP: / / http://mp.weixin.qq.com/s?__biz=MzIyMDkwODczNw==&mid=2247496250&idx=1&sn=de84c456b0cfcd8503ebee7cc002c563&ch ksm=97c66f94a0b1e68297d8815e9778a9e98e714e72620e1b62b787b88f2333a592acf701d86e7f&scene=21#wechat_redirect) * [174 JavaScript Interview knowledge summary (in)] (HTTP: / / http://mp.weixin.qq.com/s?__biz=MzIyMDkwODczNw==&mid=2247496464&idx=1&sn=156bfe75febaad620cb05a33b051c9b2&ch KSM = 97 c66ebea0b1e7a8a1e62cfe82ad83e18f1658b091253a911f3a027fcf2caf44bb987204a53b & scene = 21 # wechat_redirect) * [JS syntax ES6, ES7, ES8, ES9, ES10, ES11, ES12 new features] (HTTP: / / http://mp.weixin.qq.com/s?__biz=MzIyMDkwODczNw==&mid=2247495146&idx=1&sn=161804ab5d0f c90f266840c760a08c55&chksm=97c67044a0b1f9520cc9733f337d667a4afd101c69d231a006f36560ee4457090aad5eb0112b&scene=21#wechat_ redirect) * Conventional method summary] [19 JavaScript array (http://mp.weixin.qq.com/s?__biz=MzIyMDkwODczNw==&mid=2247495391&idx=1&sn=d071aae45529b0f91c80eb3 e429a2b3e&chksm=97c67371a0b1fa671ee3b6f7ff6c4f83907b036e5142a34a3ef4fecc8f81f41c80ad215b2b0d&scene=21#wechat_redirect) * [JavaScript The way of clean code] (HTTP: / / http://mp.weixin.qq.com/s?__biz=MzIyMDkwODczNw==&mid=2247495829&idx=1&sn=ec6d547d9b16edf90d8573bfe8aac170&chksm= 97 c66d3ba0b1e42dad254766bbbf54a52107332f935b09f54f4e7424089bfa4daf1ce5c5ab41 & scene = 21 # wechat_redirect) * [the interviewer asks the Vue performance optimization, How am I to answer] (HTTP: / / http://mp.weixin.qq.com/s?__biz=MzIyMDkwODczNw==&mid=2247496090&idx=2&sn=f72ac2a4696f543d56f93ad33777a3d7&chksm= 97c66c34a0b1e522fd216b970cda7150b67f25cf6a13da7e8522a0db84a59aa45f589d647788&scene=21#wechat_redirect) * The front-end locally stored] [easily (http://mp.weixin.qq.com/s?__biz=MzIyMDkwODczNw==&mid=2247495849&idx=1&sn=309d8209b6732eaeabbf948a7e8c4cd5&c HKSM = 97 c66d07a0b1e41108f3ca847fd3047dde60ba7e2b339e2652935589f6990b216c7feb702da0 & scene = 21 # wechat_redirect) * * * * VUE Chinese community Programming Skills ** * Industry Secrets ** * Technology trends! [image.gif](https://upload-images.jianshu.io/upload_images/2500256-8207245de2e9d6ff.gif? imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
Article source: copy from VUE Chinese community public number