JS FAQ Summary Two

Source: Internet
Author: User
Tags event listener sessionstorage

Iv. Asynchronous
Console.log (setTimeout) (function() {     console.log (GB)}) Console.log (300)
4.1 What is the difference between synchronous and asynchronous? Give an example of synchronous and asynchronous, respectively.

A: Synchronization blocks code execution, but async does not; alert is synchronous, settimeout is asynchronous

4.2 A pen question about settimeout
Console.log (1) setTimeout (function() {    Console.log (2)},0) console.log (3) setTimeout (function() {    Console.log (4)},+) console.log (5)
Print order: 1,3,5,2, after one second print 44.3 what are the scenarios where the front-end uses async?

Answer: Timed tasks: SetTimeout, SetInterval

Network requests: Ajax requests, dynamic load

Event Bindings

V. Dates and math

Knowledge Point: Date

Math: Get random number Math.random ()

Array API:

ForEach: Traversing all elements

Every: Determine if all elements meet the criteria

Some: Determine if there is at least one element that meets the criteria

Sort: Sorting

Map: Re-assemble elements to create a new array

Filter: Filters elements that match the criteria

vararr = [' A ', ' B ', ' C ', ' d ']arr.foreach (function(Item,index) {Console.log (Index,item)})vararr = [1.2.3.4]varresult = Arr.every (function(item,index) {if(item<5) {        return true}}) Console.log (Result)vararr = [1.2.3.4]varresult = Arr.some (function(item,index) {if(item<3) {        return true}}) Console.log (Result)vararr = [1.2.3.4]varARR2 = Arr.sort (function(A, b) {//sort from small to large    returnA-b//sort from big to small    returnB-A}) Console.log (ARR2)vararr = [1,2,3,4]varARR2 = Arr.map (function(item,index) {return' <b> ' +item+ ' <b> '}) Console.log (ARR2)

var arr = [1,2,3,4]
var arr2 = arr.filter (function (item,index) {
if (item<3) {
return True
}
})
Console.log (ARR2)

5.1 Get date of 2017-06-10 format

functionformatdate (DT) {if(!DT) {DT=NewDate ()}varYear =dt.getfullyear ()varmonth = Dt.getmonth () +1varDate =dt.getdate ()if(Month < 10) {        //Forcing type conversionsmonth = ' 0 ' +Month}if(Date < 10) {Date= ' 0 ' +Date}returnYear + '-' +month + '-' +Date}varDT =NewDate ()varFormatDate =formatdate (DT) Console.log (formatdate)
5.2 Getting random numbers, requiring a consistent length of string format
var random = math.random ()var random = random + ' 0000000000 '// back plus 10 0 var random = Random.slice (0,10) console.log (random)
5.3 Write a generic foreach function that can traverse objects and arrays
functionForEach (OBJ,FN) {varKeyif(objinstanceofArray) {Obj.foreach (function(Item,index) {fn (Index,item)})}Else {        //not an array is an object         for(Keyinchobj) {fn (Key,obj[key]) }}}vararr = [A.]//parameter order changed, in order to be consistent with the object traversal formatForEach (arr,function(Item,index) {Console.log (Index,item)})varobj = {x:100, y:200}foreach (obj,function(key,value) {Console.log (Key,value)})
Vi. What is the basic data structure of the JS-WEB-API 6.1 dom? What are the common APIs for Tree 6.2 DOM operations?
varDiv1=document.getelementbyid (' Div1 ')//Add new nodevarP1-document.createelement (' P ') p1.innerhtml= ' This is P1 '//add a newly created elementDiv1.appendchild (p1)//move an existing nodevarP2 = document.getElementById (' p2 ')) Div1.appendchild (p2)//get parent and child elementsvarDiv1 = document.getElementById (' Div1 '))varParent =div1.parentelementvarChild =Div1.childNodesdiv1.removeChild (child[0])//Get DOM nodevardiv1= document.getElementById (' Div1 ')//ElementsvarDivlist = document.getElementsByTagName (' div ')//CollectionConsole.log (divlist.length) console.log (divlist[0])varContainerlist = Document.getelementbyclassname ('. Container '))varPList = Document.queryselectorall (' P ')
What is the difference between the attr and the property of the 6.3 Dom node?

A: attr is a modification to the HTML tag properties

property is just a modification of the JS object's properties

//  Property var div1 = document.getElementById (' div1 ') console.log (div1.classname) div1.classname= ' abc '  Console.log (div1.classname)//attrvar p1 = document.getElementById (' p1 ') Console.log (P1.getattribute (' data-name ')) p1.setattribute (' data-name ', ' xyz ')
6.4 How to detect the browser type

Navigator/screen/location/history

// detect browser type, take chrome as an example // Navigator var ua=navigator.useragentvar ischrome = Ua.indexof (' Chrome ') console.log (ischrome)
6.5 disassembling the parts of the URL
//  Screen Console.log (screen.width) console.log (screen.height) //  Location Console.log (location.href) console.log (location.protocol) console.log (location.host) Console.log ( Location.ashpathname) Console.log (location.search) console.log (location.h)// History History.back () History.forward ( )

Vii. AJAX

XMLHttpRequest

Status Code Description

Cross-domain

Three tags that can span a domain:

<link href=xxx>

<script src=xxx>

7.1 Write an Ajax manually, without relying on third-party libraries.
var New XMLHttpRequest () xhr.open ("GET", "/api",falsefunction() {    if (xhr.readystate = = 4)        {if (xhr.state = = =){            alert (xhr.responsetext)        }    }} Xhr.send (null)
7.2 Several ways to implement cross-domain

Answer: 1. JSONP (JSONP Implementation principle: such as loading a URL, but not necessarily the server side really has such a file, the server can dynamically generate a file on request to return

Return content format such as: Callback ({x:100,y:200}))

2. Server-side Settings HTTP header

7.3 Please describe the difference between cookie,sessionstorage and localstorage?

A: 1.cookie: itself for client and server-side communication, but it has local storage capabilities, so it was "borrowed"

Use document.cookie= ..... Get and modify, but can only save 4kb, each time carried into Ajax, API needs to be encapsulated in order to use

2.sessionStorage and LOCALSTORAGE:HTML5 designed for storage, maximum capacity 5M, not portable to Ajaxzh, API simple Y

The former will be cleaned automatically and the latter will not

Viii. Event 8.1 Write a general event listener function
functionbindevent (ELEM,TYPE,SELECTOR,FN) {if(fn==NULL) {fn=Selector Selector=NULL} elem.addeventlistener (Type,function(e) {varTargetif(selector) {target=E.targetif(Target.matches (selector)) {Fn.call (target,e)}}Else{fn (e)}})}//using proxiesvarDiv1 = document.getElementById (' Div1 ')) bindevent (Div1,' Click ', ' a ',function(e) {Console.log ( This. InnerHTML)})//do not use proxiesvarA = document.getElementById (' Div1 ') bindevent (Div1,' Click ',function(e) {Console.log (a.innerhtml)})
8.2 Describe the event bubbling process

DOM tree structure, event bubbling, blocking bubbling, bubbling app

8.3 How to bind an event to each picture for an unlimited drop-down page loaded with pictures

Using proxies

Nine, the difference between Modular 9.1 window.onload and domcontentloaded?
Window.addeventlistener (' Load ',function() {    /// page will be fully loaded before execution, including pictures, videos, etc. }) Document.addeventlistener (' domcontentloaded ',function() {    //  The DOM renders and executes, and the picture and video may not have finished loading })
Process from the input URL to the detailed process of getting HTML:

1. The browser obtains the IP address of the domain name according to the DNS server

2. Send an HTTP request to this IP machine

3. The server receives, processes, and returns an HTTP request

4. Browser gets back content

9.2 briefly describes how to implement a module loader that implements basic functions like require.js.

9.3 HTTP Protocol Knowledge

(1) The browser searches for its own DNS cache first
(2) The operating system searches its own DNS cache (the browser does not find the cache or the cache is invalidated)
(3) Read the local host file
(4) A system call from the browser initiating a DNS
Broadband carrier Server View itself cache
The carrier server initiates a request for an iterative DNS resolution
The carrier server caches the results back to the operating system kernel.
The operating system kernel returns the results to the browser
The browser gets the IP address of the www.imooc.com.

(5) After the browser obtains the IP address of the domain name, it initiates the HTTP "three handshake"
(6) After the TCP/IP link is set up, the browser can send an HTTP request to the server
(7) The server has received this request, according to the path parameter, after some processing of the backend, the processed result data is returned to the browser, such as the full HTML code of the page back to the browser
(8) The browser to get the full HTML code, in the parsing and rendering of this page, the inside of the js,css, picture static resources, they are also an HTTP request, all go through the main seven steps above.
(9) The browser renders the page according to the resources it has received, and finally renders a complete page to the user.

1. Callback: Encapsulates subsequent logic in the callback function as a parameter of the starting function

2. Sync: Only one port is dealing with a single thing at a time.
Async: There is also only one port, but this port is only allocated work, the event is assigned to the following employees, there are thousands of employees waiting to help you deal with things.

3. Event-Driven: callback function registered for an event, but this callback function is not executed immediately, when the event occurs, it is called, this function is called event-driven

9.5 on-Line and rollback

A: 1. On-line: Submit the test completion code to the master branch of the Git repository

Package the current server's code and record the version number

Overwrite the code submission of the master branch to the online server and generate a new version number

2. Rollback: Package The current server's code and record the version number, back up

Unzip the previous version number of the backup, overwrite it to the online server, and generate a new version number

10.Ajax and Flash

Advantages of Ajax: 1. Accessibility 2. Openness 3. Cost 4. Ease of use 5. Easy to develop.

Advantages of Flash: 1. Multimedia processing 2. Compatibility 3. Vector Graphics 4. Client Resource Scheduling

The disadvantage of Ajax: 1. It may corrupt the browser's back-up function 2. Using dynamic page updates makes it difficult for users to save a particular state to a collection, but these are addressed in a related way.

The disadvantages of Flash: 1. binary format 2. Format private 3.flash files are often very large, users need to endure a long wait time for the first time 4. Performance issues

The following 7 global functions are included in JavaScript

Escape (), eval (), Isfinite (), IsNaN (), parsefloat (), parseint (), unescape ().

Above.

JS FAQ Summary Two

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.