Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the favorite JavaScript basic interview questions for byte beating?

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

What are the favorite JavaScript basic interview questions for byte jumping? in view of this question, this article introduces the corresponding analysis and solutions in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible way.

Note: the (xx) number in front of each question represents the frequency of this question. This JS basis is based on the questions sorted out on the front end of 30 + articles and the corresponding answers, reference links, etc.

(2) question: 0.1 + 0.2 = = 0.3? Why?

JavaScirpt uses Number types to represent numbers (integers or floating point numbers), following the IEEE 754 standard, representing a number through 64 bits (1 + 11 + 52)

1 sign bit, 0 for positive number, 1 for negative number s

11 index bit (e)

52 Mantissa, decimal part (i.e. effective number)

The maximum safe number: Number.MAX_SAFE_INTEGER = Math.pow (2,53)-1, which is 16 bits when converted to an integer, so 0. 1 = = 0. 1 because the two are equal after the significant bits are removed by toPrecision (16).

When the two numbers are added, it will first be converted to binary, and when 0.1and 0.2 are converted to binary, the Mantissa will have an infinite loop, and then the order operation will be carried out, and the JS engine will truncate the binary, resulting in a loss of accuracy.

So to sum up: the loss of precision may occur in binary conversion and order operation.

Reference link

Https://juejin.im/post/5b90e00e6fb9a05cf9080dff

(4) question: JS data type

Basic types: Number, Boolean, String, null, undefined, symbol (new to ES6), BigInt (ES2020) reference type: Object, object subtype (Array,Function)

Reference link

Https://juejin.im/post/5b2b0a6051882574de4f3d96

Https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Data_structures

Q: what is the expression of JS integers?

Represented by the Number type, following the IEEE754 standard, a number is represented by 64 bits, (1 + 11 + 52), the maximum safe number is Math.pow (2,53)-1, for 16-bit decimal. (symbol bit + exponential bit + fractional significant bit)

Q: how much storage space is there for Number ()? What if the background sends a number that exceeds the maximum number?

Math.pow (2,53), 53 is a valid number and truncation occurs, which is equal to the maximum number that JS can support.

(4) write code: the implementation function can deeply clone the basic types.

Shallow Clone:

Function shallowClone (obj) {let cloneObj = {}; for (let i in obj) {cloneObj [I] = obj [I];} return cloneObj;}

Deep cloning:

Consider the basic type

Reference type

RegExp, Date, and functions are not JSON secure

Constructor will be lost, and all constructors point to Object

Crack circular references

Function deepCopy (obj) {if (typeof obj = = 'object') {var result = obj.constructor = Array? []: {}; for (var i in obj) {result [I] = typeof obj [I] = =' object'? DeepCopy (obj [I]): obj [I];}} else {var result = obj;} return result;}

Q: event flow

Event flow is the order in which web page elements receive events. The event flow defined by "DOM2-level events" includes three stages: event capture phase, target phase, and event bubbling phase. The first event capture provides an opportunity to intercept the event. Then the actual target accepts the event. The last stage is the time bubbling phase, where you can respond to events. Although the capture phase states that response to events is not allowed in the specification, it is actually executed, so there are two opportunities to get the target object.

Event bubbling. I'm the parent element. I'm the child element.

Var sonEle = document.getElementById ('sonEle'); var parEle = document.getElementById (' parEle'); parEle.addEventListener ('click', function () {alert (' parent bubbling');}, false); parEle.addEventListener ('click', function () {alert (' parent bubbling');}, true); sonEle.addEventListener ('click', function () {alert (' child bubbling');}, false) SonEle.addEventListener ('click', function () {alert (' child capture');}, true)

When container elements and nested elements, namely, the capture phase and the bubbling phase, call the event handler: the event executes the event handler in the order of the DOM event flow:

Parent capture

Child bubbling

Child capture

Parent bubbling

And when the event is in the target phase, the event call order is determined by the writing order of the binding event. According to the above example, the event handler in the bubbling phase is called first, and then the event handler in the capture phase is called. Alert out "subset bubbling" and "subset capture" in turn.

IE compatible

AttchEvent ('on' + type, handler)

DetachEvent ('on' + type, handler)

Reference link

Https://juejin.im/entry/5826ba9d0ce4630056f85e07

Q: how did the event come true?

Based on the publish-subscribe model, the event-related code is read when the browser loads, but only when the specific event is triggered.

For example, click a button, which is an event (Event), and the code snippet responsible for handling the event is often referred to as the event handler (Event Handler), that is, the action "start the display of the dialog box".

On the Web side, what we often see is the DOM event:

For DOM0-level events, bind on-event directly to the html element, such as onclick. If canceled, dom.onclick = null. There can be only one handler for the same event, and the latter will overwrite the previous one.

DOM2-level events, register events through addEventListener, delete events through removeEventListener, an event can have multiple event handlers, execute sequentially, capture events and bubbling events

DOM3 level events, adding event types, such as UI events, focus events, mouse events

Reference link

Https://zhuanlan.zhihu.com/p/73091706

Q: what happened to a function in new

Construction call:

Create a whole new object.

This object will be connected with [[Prototype]], linking the [[Prototype]] of the new object to the object pointed to by the constructor .prototype.

This new object will be bound to the this of the function call

If the function returns no other object, the function call in the new expression automatically returns the new object

Q: new is a constructor. What happens to return true if the function returns return {}, return null, return 1?

If the function returns an object, the function call new returns the returned object of the function, otherwise the new object created by new is returned

Q: what is the use of symbol

Can be used to represent a unique variable to prevent naming conflicts. But the interviewer asked if there was any more. I don't know if I can think of anything else, but I can also use symbol to simulate private variables because it won't be traversed by conventional methods (except Object.getOwnPropertySymbols).

It is mainly used to provide traversal interface, only objects with symbol.iterator can use for ·of loop, and can deal with data structure uniformly. A traversal object is returned after the call, including a next method. After using the next method, there are two return values, value and done, indicating the value of the current execution location of the function and whether the traversal is completed.

Symbol.for () can access symbol globally

(3) Q: what is a closure?

A closure is a function that has access to variables in the scope of another function

The whole execution process of JavaScript code is divided into two stages, the code compilation phase and the code execution phase. The compilation phase is completed by the compiler, translating the code into executable code, and the scope rules for this phase are determined. The execution phase is done by the engine, the main task is to execute the executable code, and the execution context is created at this stage.

Image.png

What is the job domain?

There are only two scopes in ES5: global scope and function scope. In JavaScript, we define scope as a set of rules that manage how the engine looks up variables (variable names or function names) based on identifier names in the current scope and in nested subscopes

What is a domain chain?

First of all, we need to understand the scope chain. when accessing a variable, the compiler will first look for this identifier from the current scope, and if not, it will go to the parent scope to look up. If the parent scope has not been found, continue to look up until the global scope, and the scope chain is composed of a series of variable objects with the current scope and the upper scope. It ensures that the currently executed scope has orderly access to variables and functions that meet the access permissions.

The nature of closures

There is a reference to the parent scope in the current environment

What is closure?

A closure is a special object that consists of two parts: the execution context (code A) and the function created in that execution context (code B). When B executes, if the value of the variable object in An is accessed, then the closure is generated, and the function name of the execution context A refers to the closure in Chrome.

How to generate closures in general

Return function

Function is passed as a parameter

Application scenarios of closures

Corey bind

Module

Reference article

Https://segmentfault.com/a/1190000012646221

Q: what is NaN and what is output with typeof?

Not a Number, which means non-numeric, typeof NaN = 'number'

(2) Q: JS implicit conversion, showing that the conversion is generally non-basic type for conversion

ValueOf will be called first, and if valueOf cannot return a base type value, toString will be called

Strings and numbers

The "+" operator, if one is a string, is converted to a string and then performs string stitching

The "-" operator, converted to a number, and subtracted (- a, a * 1a * 1) can be implicitly cast.

[] + {} and {} + []

Boolean value to number

1 + true = 2

1 + false = 1

Convert to Boolean

The second in for

While

If

Ternary expression

| | (Logic OR) & (Logic and) Operand on the left |

Symbol

Cannot be converted to a number

Can be converted to a Boolean value (all true)

Can be converted to the string "Symbol (cool)"

Loose equality and strict equality

Loose equality allows cast, while strict equality does not

Strings and numbers

Convert to a number and then compare

Other types and Boolean types

Convert the Boolean type to a number, and then continue the comparison

Object and non-object

Execute the ToPrimitive (object) of the object and then continue the comparison

List of false values

Undefined

Null

False

+ 0,-0, NaN

"

(2) Q: know this. What does bind,call,apply mean?

They are all methods of functions.

Call: Array.prototype.call (this, args1, args2]) apply: Array.prototype.apply (this, [args1, args2]): ES6 was used to expand array calls before, foo.appy (null, []), after ES6. Operator

New binding > Show binding > implicit binding > default binding

If you need to use the Corialization of bind and the array deconstruction of apply, bind to null and create a DMZ object using Object.create (null) as much as possible

Four rules:

Default binding, no other modifications (bind, apply, call), definition points to global object in non-strict mode, definition points to undefined in strict mode

Function foo () {console.log (this.a);} var a = 2; foo ()

Implicit binding: whether the calling location has a context object, or whether it is owned or contained by an object, then the implicit binding rule binds the this in the function call to this context object. Moreover, only the upper or last layer of the object attribute chain plays a role in the calling location.

Function foo () {console.log (this.a);} var obj = {a: 2, foo: foo,} obj.foo (); / / 2

Show binding: the binding this is displayed by running call and apply on the function

Function foo () {console.log (this.a);} var obj = {a: 2}; foo.call (obj)

Show hard bindings for bindings

Function foo (something) {console.log (this.a, something); return this.a + something;} function bind (fn, obj) {return function () {return fn.apply (obj, arguments);};} var obj = {a: 2} var bar = bind (foo, obj)

New binding, new calls the function to create a brand new object and binds the object to the this of the function call.

When New is bound, if new is a hard-bound function, the hard-bound this will be replaced with the new object created by new.

Function foo (a) {this.a = a;} var bar = new foo (2); console.log (bar.a)

(4) ask: handwritten bind, apply, call

/ / call

Function.prototype.call = function (context,... args) {

Context = context | | window

Const fnSymbol = Symbol ("fn")

Context [fnSymbol] = this

Context [fnSymbol] (. Args)

Delete context [fnSymbol]

}

/ / apply

Function.prototype.apply = function (context, argsArr) {

Context = context | | window

Const fnSymbol = Symbol ("fn")

Context [fnSymbol] = this

Context [fnSymbol] (. ArgsArr)

Delete context [fnSymbol]

}

/ / bind Function.prototype.bind = function (context,... args) {context = context | | window; const fnSymbol = Symbol ("fn"); context [fnSymbol] = this; return function (. _ args) {_ args = _ args.concat (args); context [fnSymbol] (. _ args); delete context [fnSymbol];}}

(3) question: how long will it take for setTimeout (fn, 0) to be implemented, Event Loop

SetTimeout is placed in the queue in order, and then waits for the function call stack to be cleared before execution. The order in which these operations enter the queue is determined by the set delay time.

Handwritten inscription: Promise principle

Class MyPromise {constructor (fn) {this.resolvedCallbacks = []; this.rejectedCallbacks = []; this.state = 'PENDING'; this.value =''; fn (this.resolve.bind (this), this.reject.bind (this));} resolve (value) {if (this.state = = 'PENDING') {this.state =' RESOLVED'; this.value = value This.resolvedCallbacks.map (cb = > cb (value));}} reject (value) {if (this.state = 'PENDING') {this.state =' REJECTED'; this.value = value; this.rejectedCallbacks.map (cb = > cb (value)) }} then (onFulfilled, onRejected) {if (this.state = 'PENDING') {this.resolvedCallbacks.push (onFulfilled); this.rejectedCallbacks.push (onRejected);} if (this.state =' RESOLVED') {onFulfilled (this.value);} if (this.state = 'REJECTED') {onRejected (this.value);}

Question: js script loading problem, async, defer problem

If you rely on other scripts and DOM results, use defer

Use async if you are not strongly dependent on DOM and other scripts

references

Https://mp.weixin.qq.com/s/pw5lfFeNagmjFj45ygl2dQ

Q: how can I tell if an object is empty?

Object.keys (obj). Length = 0

Q: external js files are loaded first or executed by onload first. Why?

Onload is executed after loading is completed.

Q: how to add event monitoring, two kinds

Onclick and addEventListener

Q: event propagation mechanism (event flow)

Bubbling and capture

(4) Q: talk about the inheritance of prototype chain and prototype chain

All ordinary [[Prototype]] chains eventually point to the built-in Object.prototype, which contains many common features in JavaScript

Why can you create a "class" with a special property: by default, all functions have a common and non-enumerable property called prototype, which points to another object, which is often referred to as the prototype of the function

Function Person (name) {this.name = name;} Person.prototype.constructor = Person

When a call to the new constructor occurs, the [[Prototype]] of the new object created is linked to the object pointed to by Person.prototype. This mechanism is called prototype chain inheritance.

Methods are defined on prototypes and properties are defined on constructors

First of all, let's talk about the relationship between the JS prototype and the instance: each constructor has a prototype object (prototype), which contains a pointer property to this constructor, an instance generated by a constructor call through new, and this instance contains a pointer to the prototype object, which is linked to the prototype object through [Prototype].

Then let's talk about the lookup of attributes in JS: when we try to reference a property of an instance object, we find it in this way. First, we look for whether there is this property on the instance object. If not, look for it on the object pointed to by the prototype of the constructor of the instance object. If we can't find it yet, look for it on the prototype prototype object of the constructor pointed to by the prototype object.

What is a prototype chain: this looks like a chain step by step and is linked through the [[Prototype]] attribute, so it is called a prototype chain.

What is prototype chain inheritance, analogical class inheritance: when there are two constructors An and B, linking the prototype object of one constructor A to the prototype object of another B constructor through its [[Prototype]] property, this process is called prototype inheritance.

A more correct explanation of the standard answer

What is a prototype chain?

When an object looks for a property, if it is not found in itself, it will find its own prototype. If the prototype has not been found, it will continue to look for the prototype of the prototype until the prototype of Object.prototype is found, when the prototype is null, and the search stops. This step-up search chain through a prototype link is called a prototype chain.

What is prototype inheritance?

One object can use the properties or methods of another object, which is called inheritance. Specifically, by setting the prototype of this object to another object, according to the rules of the prototype chain, if you look for an object property and when it does not exist, it will find another object, which means that one object can use the properties and methods of another object.

Reference link

Https://zhuanlan.zhihu.com/p/35790971

Q: tell me what you know about JS

Is a prototype-based dynamic language, the main unique features are this, prototype and prototype chain.

Strictly speaking, JS is divided into: language standard part (ECMAScript) + host environment part

Language standard section

ES6 was released in 2015 and many new features have been introduced to make it possible to write large-scale projects. Since 2015, the standard has been changed by an annual code.

Host environment part

In browser hosting environment, including DOM + BOM, etc.

In Node, the hosting environment includes files, databases, networks, interaction with the operating system, etc.

Q: what are the functions that an array can call?

Push

Pop

Splice

Slice

Shift

Unshift

Sort

Find

FindIndex

Functional programming methods such as map/filter/reduce

There are also some methods on the prototype chain: toString/valudOf

Q: how to determine the type of array

Array.isArray

Q: is the arguments in the function an array? Class array to the method of the array to understand?

It's a class array. It belongs to the category of duck type. It looks like an array.

... Operator

Array.from

Array.prototype.slice.apply (arguments)

Q: have you ever used TypeScript? What is its function?

Adding type support for JS, as well as providing support for the latest version of ES syntax, is conducive to team collaboration and troubleshooting to develop large-scale projects

Q: have you ever used PWA? What is the principle of using serviceWorker?

Progressive Web Application (PWA) is a concept put forward by Google at the end of 2015. It's basically a web application, but it looks and feels like native app. Websites that support PWA can provide functions such as offline work, push notifications, and device hardware access.

Service Worker is a script that browsers run independently of web pages in the background, opening the door to functions that do not require web pages or user interaction. Now they include features such as push notification and background synchronization. In the future, Service Worker will support other features such as periodic synchronization or geographic fencing. The core function discussed in this tutorial is to intercept and process network requests, including programmatically managing responses in the cache.

Reference link

Https://juejin.im/post/5e26aa785188254c257c462d#heading-8

Q: prototype was used to implement inheritance before ES6

Object.create () creates a "new" object and then associates the [[Prototype]] inside the object to the object you specify (Foo.prototype). Object.create (null) creates an empty [[Prototype]] linked object that cannot be delegated.

Function Foo (name) {this.name = name;} Foo.prototype.myName = function () {return this.name;} / / inherit the attribute, and create a backup Bar.prototype = Object.create (Foo.prototype) by borrowing the constructor to call function Bar (name, label) {Foo.call (this, name); this.label = label;} / / inheritance method / / must be set back to the correct constructor, otherwise Bar.prototype.constructor = Bar; / / Bar.prototype.myLabel = function () {return this.label;} var a = new Bar ("a", "obj a"); a.myName (); / / "a" a.myLabel (); / / "obj a" after the previous step will occur

Q: if a constructor bind an object, will the instance created with this constructor inherit the properties of that object? Why?

Will not inherit, because according to the four rules of this binding, new binding takes precedence over bind display binding. When a constructor call is made through new, a new object is created, which replaces the object binding of bind as the this of this function, and returns the newly created object if the function does not return an object.

(3) what is the difference between arrowhead function and ordinary function? Can the arrow function be used as a constructor?

Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community

Ordinary functions are defined by the function keyword, and this cannot be used in conjunction with lexical scope. Binding at run time only depends on how the function is called, where it is called, and where it is called. (depends on the caller, and whether it runs independently)

The arrow function is defined using an operation called "fat arrow". Instead of applying the four rules of the ordinary function this binding, the arrow function determines this according to the scope of the outer layer (function or global), and the binding of the arrow function cannot be modified (neither can new).

There are two methods inside a function: [[Call]] and [[Construct]]. When a function is called through new, the [[construct]] method is executed to create an instance object, and then the function body is executed to bind the function's this to the instance object.

When called directly, execute the [[Call]] method and execute the function body directly

The arrow function does not have a [[Construct]] method and cannot be used as a constructor call. An error is reported when a function call is made using new.

Arrow functions are often used in callback functions, including event handlers or timers

Both the arrow function and var self = this attempt to replace the traditional this operating mechanism and pull the binding of this back to the lexical scope

No prototype, no this, no super, no arguments, no new.target

Cannot be called through the new keyword

Function foo () {return (a) = > {console.log (this.a);}} var obj1 = {a: 2} var obj2 = {a: 3} var bar = foo.call (obj1); bar.call (obj2)

references

Https://segmentfault.com/a/1190000015162781

Q: do you know ES6's Class? Do you know the Static keyword?

Add methods directly to the function object of this class, rather than to the prototype object of the function object

(3) Q: event cycle mechanism (Event Loop)

The event loop mechanism as a whole tells us the execution order of JavaScript code Event Loop that is event loop, which refers to a mechanism of browser or Node to solve the problem that javaScript single thread will not block when it runs, that is, we often use the principle of asynchronous.

First execute the macro task queue, then execute the micro task queue, and then start the next round of event loop, continue to execute the macro task queue, and then execute the micro task queue.

Macro task: script/setTimeout/setInterval/setImmediate/ Imax O / UI Rendering

Micro task: process.nextTick () / Promise

The appellate setTimeout and setInterval are all task sources, and it is the tasks they distribute that really enter the task queue.

Priority

SetTimeout = setInterval a queue

SetTimeout > setImmediate

Process.nextTick > Promise

For (const macroTask of macroTaskQueue) {handleMacroTask (); for (const microTask of microTaskQueue) {handleMicroTask (microTask);}}

Reference link

Https://juejin.im/post/59e85eebf265da430d571f89

(2) handwritten questions: array flattening

Function flatten (arr) {let result = []; for (let I = 0; I < arr.length; iTunes +) {if (Array.isArray (arr [I])) {result = result.concat (flatten (arr [I]));} else {result = result.concat (arr [I]);} return result;} const a = [1, [2, [3,4]; console.log (flatten (a))

Handwritten question: realizing Corey

Set some parameters in advance

What is Corialization: a function that receives function An and returns a new function that can handle the remaining parameters of function A.

Function createCurry (func, args) {var argity = func.length; var args = args | | []; return function () {var _ args = [] .slice.apply (arguments); args.push (. _ args); if (args.length < argity) {return createCurry.call (this, func, args);} return func.apply (this, args);}}

Handwritten questions: array deduplication

Array.from (new Set ([1,1,2,2]))

Question: let closure

Let will produce a temporary dead zone. In the current execution context, the variable will be promoted, but it will not be initialized. Therefore, in the execution phase of the execution context, if the execution code has not been executed to the variable assignment, an error will be reported if the variable is referenced. The variable is not initialized.

Q: variable promotion

When the function is running, it first creates the execution context, then stacks the execution context, and then starts running the execution context when the execution context is at the top of the stack.

In the process of creating the execution context, you will do three things: create a variable object, create a scope chain, and determine the this point. In the process of creating a variable object, you will first create an attribute for arguments with a value of arguments, then scan the function function declaration, create a reference of the same name attribute with the value of the function, and then scan the var variable declaration and create an attribute of the same name with the value of undefined. This is variable promotion.

How to use instance

The left can be any value, and the right can only be a function

Hello tuture' instanceof String / / false here are the answers to the questions about byte jump's favorite JavaScript basic interview questions. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel for more related knowledge.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report