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 common JavaScript interview questions?

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

What are the common JavaScript interview questions? for this question, this article introduces the corresponding analysis and answers in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible way.

1. How to understand the this keyword in JS?

This represents the current object, and the direction of the this is determined according to the context of the call. By default, it points to the window object.

Global environment: the global environment is inside, and the this here always points to the window object.

Local environment:

1. The function is called directly under the global scope, and this points to window.

two。 Object function call, which object call points to the object.

3. The object is instantiated using new, and the this in the constructor points to the instantiated object.

4. Use call or apply to change the direction of the this.

2. What is the scope in JavaScript?

In JavaScript, each function has its own scope. A scope is basically a collection of variables and rules on how to access them by name. Only code in the function can access variables within the scope of the function.

Variable names in the same scope must be unique. One scope can be nested within another scope. If one scope is nested within another scope, code in the innermost scope can access variables in the other scope.

3. What is closure?

When I first explained the closure, I often said the function in the function; however, it did not correctly describe the exact meaning of the closure.

A closure creates a closed lexical scope within another scope. It usually returns automatically to generate this lexical environment. This environment consists of any local variables that are in scope when the closure is created. It is like a miniature factory that uses these raw materials to produce products with specific functions.

4. Explain the equality in JavaScript.

There are strict comparisons and type conversion comparisons in JavaScript:

To compare strictly (for example, =) to check whether two values are equal if forced transformation is not allowed.

An abstract comparison (for example, = =) checks whether two values are equal if forced transformations are allowed.

Var a = "42"

Var b = 42

A = = b; / / true

A = = b; / / false

Copy code if any of the values being compared may be true or false, use = instead of = =

If any of the values being compared are these specific values (0, ", or []), use = instead of = =

In other cases, you can safely use =. Not only is it safe, but in many cases, it simplifies code and improves code readability.

5. Explain the promotion of variables.

Variable promotion is the default behavior of JavaScript, which means that all variable declarations are moved to the top of the current scope, and variables can be used before declaration. Initialization is not promoted, which only acts on the declaration of variables.

Var x = 1

Console.log (x +'- -'+ y) / / 1--undefined

Var y = 2

6. How to understand event delegation

Binding event listeners to the DOM tree and using JS event handlers is a typical way to handle client event responses. In theory, we could attach listeners to any DOM element in HTML, but because of event delegation, this is wasteful and unnecessary.

What is event delegation?

This is a technique for getting event listeners on parent elements to affect child elements as well. In general, event propagation (capture and bubbling) allows us to implement event delegates. Bubbling means that when a child element (target) is triggered, the parent element of that child element can also be triggered layer by layer until it encounters the original listener of the DOM binding (the current target). The capture attribute converts the event phase to the capture phase, moving the event down to the element; therefore, the trigger direction is the opposite of the bubbling phase. The default value for capture is false.

7. Explain the strict mode (strict mode)

Strict patterns are used to standardize normal JavaScript semantics. Strict mode can be embedded in non-strict mode with the keyword 'use strict'. Code after using strict mode should follow the strict syntax rules of JS. For example, a semicolon is used after each statement is declared.

8. Explain null and undefined in JavaScript.

There are two underlying types in JavaScript: null and undefined. They represent different meanings: not initialized yet: undefined; null: null.

/ / null and undefined are two different objects

Null = = null / / true

Null = null / / true

Null = = undefined / / true

Null = undefined / / flase

9. Explain the values and types in JavaScript.

JavaScript provides two data types: basic data types and reference data types. The basic data types are:

String

Number

Boolean

Null

Undefined

Symbol

The reference data types are:

Object

Array

Function

10. Explain the event bubbling and how to stop it?

Event bubbling means that the deepest nested element triggers an event, which is then triggered on the parent element in the nesting order. One way to prevent events from bubbling is to use event.cancelBubble or event.stopPropagation () (below IE 9).

What is the role of 11._window.onload?

_ window.onload is an event called after the document and resources have been loaded, ensuring that the js has already loaded the element when it gets the element.

twelve。 Tell me about your understanding of the domain chain?

Scope chain is a lookup mechanism in js. From the current scope lookup, the current scope does not look up to the outermost layer, and if it can not be found, it is is not define.

13. What is the classification of timers? What is the difference and usage between them?

There are two kinds of timers in Js: setInterval: intermittent execution, setTimeout: delayed execution

SetInterval (function, time) time unit ms

Syntax: setInterval (function () {}, 1000); execute the function every second

Generally used for countdown, rotation chart

SetTimeout (function, time) time unit ms

Syntax: setTimeout (function () {}, 1000); delay the execution of the function once per second, only once

Generally used for advertising, advertising pop-up layer

14. Remove the following string and remove the special characters to sort the string in the order in which the number comes before the letter.

As follows: "1233fddfd&3434fdsaff&454545&4545444rfdsfds&545gdsgs"

Var str = "1233fddfd&3434fdsaff&454545&4545444rfdsfds&545gdsgs"

Var n = ""

Var s = ""

For (var iTuno Bandi)

If ((str [I] > = zero & str[ I] = 97&&str.charCodeAt (I) arr [juni1]) {/ /

Var temp = arr [j]

Arr [j] = arr [juni1]

Arr [jacks 1] = temp

}

}

}

How 20.DOM adds, removes, moves, copies, creates, and finds nodes

Get child node

Parent node.children

Parent Node .childNodes

Get parent node

Child node [xss_clean]

Child Node .offsetParent

Create

Document.createElement ('label signature')

Document.createTextNode ('text content')

Add

Parent node .appendChild (child node)

Parent node.insertBefore (newChild,refChild)

Copy

Copied Node .cloneNode (true)

Delete:

Node .remove ()

Parent node .removeChild (child node)

Replace

Parent Node .replaceChild (newChild,refChild)

21. What is a window object? What is a document object?

Window is the largest object in js, represents a window, and contains document.

An document document object that represents a HTML.

What is the difference between 22.offsetWidth, clientWidth and scrollTop?

OffsetWidth: occupies a wide space, including content width + padding+ around border.

ClientWidth: visual width, including content width + left and right padding.

ScrollTop: the page is rolled up high.

23. How do I get the search content in the url address?

_ window.location.search

24. What is the difference between event, IE and Firefox's event mechanism?

IE's event stream is bubble flow, while Firefox supports both bubble flow and capture flow.

25. What's the difference between event binding and normal events.

Label. Event: if you add the same event to the same element, the following will overwrite the previous event binding: you can add the same event to the same element and will not be overwritten.

twenty-six。 Explain the flow of events?

Event capture phase: when an event occurs, the event is passed from window to the child element in order to determine the target phase: determine the event target event bubbling phase: the event target begins to process the event, and after processing, the event is passed to the parent element in turn, until the window event is bubbling, and ie is only bubbling.

twenty-seven。 How many events are there in the drag effect?

Press onmousedown, drag onmousemove, and pop up onmouseup.

What are the advantages and disadvantages of 28.cookie?

Advantages: high scalability and availability

1. With good programming, you can control the size of session objects saved in cookie.

two。 Through encryption and secure transmission technology (SSL), reduce the possibility of cookie being cracked.

3. Only store insensitive data in cookie, even if it is stolen, there will be no significant loss.

4. Control the lifetime of cookie so that it does not last forever. The thief is likely to get an expired cookie.

Disadvantages:

Restrictions on the number and length of 1.Cookie. Each domain can only have a maximum of 20 cookie, and each cookie cannot exceed the length of 4KB, otherwise it will be truncated.

two。 Security issues. If cookie is intercepted, that person can get all the session information. Even encryption does not help, because the interceptor does not need to know the meaning of cookie, he only needs to forward cookie as is to achieve his goal.

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

Because of these disadvantages (mainly because the size and number of cookie are limited, and every time you request a new page, Cookie is sent, which virtually wastes bandwidth, and cookie also needs to specify a scope and cannot be called across domains), after IE8, there will be a web storage; that exists only to cache data locally. But Cookie is also impossible or missing: the role of Cookie is to interact with the server and exists as part of the HTTP specification.

What is the difference and function between 29.call () and apply ()?

All are used to change the direction of this, and there will be some differences in the process of passing values:

Call (direction of this, parameter 1, parameter 2...)

Apply (direction of this, [parameter 1, parameter 2 …])

thirty。 The process of creating an ajax.

Function ajax (json) {

Json.data = json.data | | "; / / null if there is no request parameter

Json.contentType = json.contentType | | "application/x-www-form-urlencoded"; / / if there is no character encoding, use the default

/ / 1. Create object

If (window.XMLHttpRequest) {/ / normal

Var ajax = new XMLHttpRequest ()

} else {/ / compatible with ie6

Var ajax = new ActiveXObject ("Microsoft.XMLHTTP")

}

/ / 2. Establish a connection

If (json.type.toUpperCase () = = "get" .toUpperCase ()) {

Ajax.open ("GET", json.url+ "?" + json.data,true)

/ / 3. Send a request

Ajax.send ()

} else {

Ajax.open ("POST", json.url,true)

/ / 3. Set the request header ajax.setRequestHeader ("Content-type", json.contentType+ "; charset=utf-8")

/ / 4. Send a request

Ajax.send (json.data)

}

/ / 4. Monitoring result

Ajax.onreadystatechange = function () {

If (ajax.readyState = = 4) {

If (ajax.status = = 200) {

Json.success (ajax.response)

}

}

}

}

The difference between get and post when 31.ajax requests, and when to use post.

The GET request passes the parameters after the URL, while the POST request is sent to the WEB server as the entity content of the HTTP message. Of course, this distinction is not visible to the user in an Ajax request.

GEt transmission data capacity is small, insecure, post transmission data content is large, more secure; when sending some data to the server, it is safer to choose post.

How to interpret json data when 32.ajax requests.

If it is a string of json:eval ("(" + ajax.response+ ")").

If it is a local json file: JSON.parse (data).

thirty-three。 What's the difference between synchronous and asynchronous?

Async: other things can be done when the client and server request data.

Synchronization: nothing else can be done when the client and server request data.

thirty-four。 Common http status codes?

You don't need to know everything, just the common ones, such as 200 404 503.

200 status code: indicates that the request was successful, and the desired response header or data body of the request will be returned with this response.

Status code: indicates that the request was successful and the server created a new resource, and its URI has been returned with the Location header information. If the required resources cannot be established in time, you should return '202 Accepted'.

202 status code: the server has accepted the request, but has not yet processed it.

301 status code: the requested resource has been permanently moved to a new location. When the server returns this response (the response to a GET or HEAD request), it automatically moves the requestor to a new location.

Status code: the requested resource temporarily responds to the request from a different URI, but the requester should continue to use the original location for future requests.

304 the requested web page has not been modified since the last request. When the server returns this response, the web page content is not returned. If the page has not changed since the requestor's last request, you should configure the server to return this response (called the If-Modified-Since HTTP header).

301 status code: the requested resource has been permanently moved to a new location. When the server returns this response (the response to a GET or HEAD request), it automatically moves the requestor to a new location.

Status code: the requested resource temporarily responds to the request from a different URI, but the requester should continue to use the original location for future requests. The requested web page has not been modified since the last request. When the server returns this response, the web page content is not returned. If the page has not changed since the requestor's last request, you should configure the server to return this response (called the If-Modified-Since HTTP header).

401 status code: the request requires authentication. For web pages that need to log in, the server may return this response.

403 status code: the server understands the request but refuses to execute it. Unlike the 401 response, authentication does not provide any help, and the request should not be submitted repeatedly.

404 status code: the request failed and the desired resource was not found on the server. There is no information to tell the user whether the situation is temporary or permanent. If the server knows, the 410 status code should be used to inform the old resource that it is permanently unavailable due to some internal configuration mechanism problem, and there is no address to jump to. The 404 status code is widely used when the server does not want to reveal exactly why the request was rejected or there is no other suitable response available.

500 status code: the server encountered an unexpected condition that prevented it from completing the processing of the request. In general, this problem occurs when the server's code goes wrong.

503 status code: the server is currently unable to process requests due to temporary server maintenance or overload. Usually, this is a temporary state and will recover over time.

What actions in 35.js can cause memory leaks?

1) memory leak caused by unexpected global variable function leak () {leak= "xxx"; / / leak becomes a global variable and will not be recycled}.

2) forgotten timer or callback.

3) memory leaks caused by closures.

36.What is the difference between the $(document) .ready () method and _ window.onload?

The difference between _ window.onload and ready

1._window.onload will overwrite the difference of the previous ready, will not overwrite, will overlay.

When documents and resources such as 2._window.onload are loaded, ready is called as soon as the document is loaded.

thirty-seven。 How to solve the cross-domain problem?

Cross-domain is solved through jsonp, that is, a js file is introduced through the src attribute of the script tag, and the data is returned to KaTeX parse error: Expected 'EOF', got' &'at position 34:... In the script src='url& requests callback=showDa... .ajax () method, you only need to configure a dataType:'jsonp', to initiate a cross-domain request.

What are the common JavaScript interview questions? the answers are shared here. 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