Front-end interview questions (JavaScript)

Introduce the basic data types of javaScript?

Basic data types : Number , String Boolean , Null , undefined

object t is the parent object of all objects in javascript

Data encapsulation objects: object, Array, Boolean, Number, String

Other objects: Function, Arguments, Math, Date, Error, RegExp

Other data types: Symbol

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

What are the built-in objects of js?

Commonly used objects in js are: Arguments  function parameter collection     Array  array     Boolean Boolean  object  Data  date time  Error  exception object     Function function  constructor     Math  mathematical object    Number numeric object  Object   basic object RegExp  regular expression object   String string object

How many ways does js create objects?

factory way, constructor way, prototype mode, hybrid constructor prototype mode, dynamic prototype way

How many ways to create functions?

Function declaration function fun(){ }

function expression let fun =function(){ }

Function object type let fun = new function("parameter", "function body")

How to convert an array into a json object, and then convert it back?

What data types does javascript's typeof return

object number function boolean underfind string

How many ways are there to delay loading of js?

Six types: defer attribute, async attribute, dynamically create dom method, use jquery's getScript method, use setTimeout delay method, let js load last.

HTML 5 defines the async attribute for the <script> tag. After adding this attribute, the script and HTML will be loaded together (asynchronously) and the code will run smoothly.

When the browser encounters an async script, it will not block the rendering of the page, but will directly download and run it. But the problem with this is that the running order of different scripts cannot be controlled, but the scripts will not prevent the display of the remaining pages.

The async attribute only applies to external script files.

What is the difference between putting the Script tag at the bottom of the page before and after closing the body?

How will the browser parse them? If it is placed before the closure of the body, it will block the loading of other resources; if it is placed after the closure of the body, it will not affect the loading of elements in the body

The difference between split() join()

The former is in the form of cutting into an array, and the latter is converting an array into a string

join() method : used to put all the elements in the array into a string.

Elements are separated by the specified delimiter.

split() method : used to split a string into an array of strings.

Array methods pop() push() unshift() shift()

Add at the end of Push() pop() delete at the end Unshift() add shift() at the head and delete at the head

What are closures?

The js closure is a function nested within a function, and the sub-function refers to the variable of the external function. When the sub-function is called by return, the variable will always remain in memory.

How to add, remove, move, copy, create and find nodes?

1) Create a new node

createDocumentFragment() //Create a DOM fragment

createElement() //Create a specific element

createTextNode() //Create a text node

2) Add, remove, replace, insert

appendChild() //add removeChild() //remove replaceChild() //replace insertBefore() //insert

3) Find

getElementsByTagName() //By the tag name getElementsByName() //By the value of the Name attribute of the element getElementById() //By the element Id, uniqueness

How does Javascript implement inheritance?

Prototype chain inheritance, borrowing constructor inheritance, compositional inheritance, parasitic inheritance, parasitic compositional inheritance

Could you please talk about the disadvantages of cookies?

Disadvantages: 1. Limits on the number and length of `Cookie`. Each domain can only have 20 cookies at most, and the length of each cookie cannot exceed 4KB, otherwise it will be cut off.

2. Security issues. If the cookie is intercepted, that person can obtain all session information. Even encryption doesn't help, because the interceptor doesn't need to know the meaning of the cookie, he can achieve his goal as long as he forwards the cookie as it is.

3. Some states cannot be saved on the client side. For example, to prevent repeated form submissions, we need to keep a counter on the server side. If we store this counter on the client side, it won't do anything.

JavaScript this pointer, closure, scope

this: points to the calling context

Closure: the inner scope can access the variables of the outer scope

Scope: defining a function opens up a local scope, and the entire js execution environment has a global scope

 What exactly does the new operator do?
1. Create an empty object, and the this variable refers to the object, and also inherits the prototype of the function.
 2. Properties and methods are added to the object referenced by this.
 3. The newly created object is referenced by this, and finally returns this implicitly.
Anti-shake and throttling
anti-shake
    In the scrolling event, it is necessary to do a complex calculation or realize the anti-secondary click operation of a button. It can be achieved by function anti-jitter

 The essence of throttling
    anti-shake and throttling is different. Anti-jitter is to turn multiple executions into the last execution, and throttling is to turn multiple executions into execution at intervals

Same-origin policy of js Same-origin
: Same protocol, same domain name, same port
 Different origin: As long as one of the protocols, domain names, and ports is different, different sources will generate cross-domain same-
 origin policy Main function: Restrict mutual access between servers of different origins , improve the security of browser access to web pages

What is an event proxy?
That is to delegate the event that originally needs to be bound to the parent element, and let the parent element take on the role of event monitoring.
The principle of event proxy is the event bubbling of DOM elements. The advantage of using event proxy is that it can improve performance,
save a lot of memory usage, and reduce event registration.
It can realize that when new sub-objects are added, there is no need to bind them again.

 What is the difference between forEach and map in an array?
The same point of forEach and map
The same point is to loop through each item in the array

The forEach and map methods support 3 parameters each time the anonymous function is executed. The parameters are item (each current item)
, index (index value), and arr (the original array).
This in the anonymous function points to the window and can only be traversed. The array will not change the original array 

 The difference between
 the map method
1. The map method returns a new array, and the elements in the array are the values ​​processed by calling the function of the original array.
2. The map method does not detect empty arrays, and the map method does not change the original array.
3. Browser support: chrome, Safari1.5+, opera all support, IE9+, if arr is an empty array, the
map method returns an empty array.

 forEach method
1. The forEach method is used to call each element of the array and pass the element to the callback function
2. forEach will not call the callback function for an empty array. Regardless of whether arr is an empty array,
forEach returns undefined. This method just executes each item in the array as a parameter of callback once

 What is the garbage collection mechanism in JS, which one is commonly used, and how to deal with it?
The garbage collection mechanism of JS is to prevent memory leaks. The meaning of memory leaks is that when a piece of memory is no longer needed, the garbage collection mechanism still exists in this piece of memory. The mechanism is to
find unused variables intermittently and irregularly, and release them delete the memory they point to.

The most common way of garbage collection in JS is
 to mark and clear
the working principle: when a variable enters the environment, mark this variable as "entering the environment". When a variable leaves the environment,
it is marked as "leaving the environment". Reclaim memory if marked as "leaving the environment"

 Workflow:
The garbage collector will mark all the variables stored in the memory at runtime, remove the variables in the environment
and the variables referenced by the variables in the environment, and then mark them as Variables to be deleted
Garbage collector completes memory cleanup, destroys those marked values ​​and reclaims the memory space they occupy

Several traversal loop methods of js
forEach() : The parameter is a callback function, which will traverse all items in the array. The callback function accepts three parameters, namely value, index, self; forEach has no return value    
 map() : same as forEach, at the same time The callback function returns data to form a new array. The map returns    
 every() : the same as forEach, and the callback function returns boolean values, all of which are true, and every returns true    
 some() : the same as forEach, and the callback function returns boolean values, as long as there is one is true, returned true by some

Pros and cons of iframes?

Advantages: 1. Solve the loading problem of slow-loading third-party content such as icons and advertisements

2. Security sandbox

3. Load scripts in parallel

Disadvantages: 1. iframe will block the Onload event of the main page

2. Even if the content is empty, it will take time to load

3. No semantics

 String function:
                .charAt(index);//charAt() method can return the character at the specified position.
                .charCodeAt(index);//The method can return the Unicode encoding of the character at the specified position. The return value is an integer between 0 - 65535.
                String.fromCharCode();//The method returns the string created by the specified sequence of UTF-16 code units
                .indexOf();
                .lastIndexOf();
                .concat();
                .split();//Split the string into Array split("")
                .slice();
                .substring();
                .substr();//The new version discards and recommends substring
  
                .replace(searchValue,replaceStr|function);//Text replaces the first character returned New string
                .replaceAll(searchValue,replaceStr|function);//Text replacement matches all characters
                .toLowerCase();//Convert all English characters to lowercase
                .toUpperCase();//Convert all English strings to uppercase.repeat
                ();//Copy the specified number of
                characters.trim();//Remove leading and trailing spaces.
    Array function:
                indexOf(); The search item is in the array The position of the first occurrence does not return -1
                push(); Add one or more items to the end of the array
                pop(); Delete the last item of the array and return the deleted item
                shift(); Delete the first item of data and return the deleted item
                unshift (); Insert one or more items to the beginning
                of the array sort(); Sort the elements in the array.
                slice(); Get the array fragment and return it without changing the original array
                splice(); Intercept, delete, modify the array item, and return the received array Affect the result. Will change the original array
                concat(); Merge the array
                join(); Connect each item in the array with a separator to form a string
                reverse(); Flip the array
                map(); Traverse each item in the array and return a new array
                filter(); filter the array
                forEach(); traverse the array

call, apply, bind difference
call(object pointed to by this, parameter 1, parameter 2, parameter 3, ...)
apply(object pointed to by this, [parameter 1, parameter 2, parameter 3, ...])
bind( The object pointed to by this, parameter 1, parameter 2, parameter 3, ...)
are the same:
call, apply, and bind are all methods of the function prototype, and
they all change the internal this point when the function is called.
The first parameter is The object pointed to by this inside the function
Differences:
call starts from the second parameter as a parameter of the function, and the parameter is passed in a single pass, and cannot be passed as an array of parameters;
apply starts from the second parameter as a parameter of the function, and the second parameter It is an array,
which contains all the parameters of the function.
 bind starts from the second parameter as the parameters of the function, and the parameters are passed in a single pass, and cannot be passed in an array of parameters,
and return a function pointed to by this inside the bound function

What should be paid attention to when using arrow functions?
(1) With the arrow function, this does not point to the window, but the parent (pointing is variable) (
2) The arguments object cannot be used
(3) It cannot be used as a constructor, which means that the new command cannot be used , otherwise an error will be thrown
(4) The yield command cannot be used, so the arrow function cannot be used as a Generator function

What is a shallow copy and a deep copy of an object, what is the difference, and how to implement a deep copy of an object

Shallow copy copies the address of the reference to the object

Deep copy is to traverse the object recursively until the value is a basic data type and then copy

Shallow copying the values ​​of the old and new objects will affect each other. Deep copies do not affect each other

Implementation process: define a deepcopy function, receive a parameter,

Use typeof to determine whether the parameter is an object

Then use Array.isArray to judge whether it is an array, if it is, an empty array will be generated, and if it is not, an empty object will be generated

Perform a for in loop on the parameters to determine whether each item is an object. If it is, call itself and assign it to a new object. Otherwise, assign a value before and return the new object.

json..parse(Json.stringify(obj)) can also perform deep copying of objects and arrays, but cannot copy functions

Guess you like

Origin blog.csdn.net/H_hl2021/article/details/121751152
Recommended