1. What data types are returned by javascript typeof.
Answer: string, number, Boolean, undefined, the function of the object
2. What are the three types of cast and two types of implicit cast?
Answer: mandatory (parseInt parseFloat, number) implicit (= = = = =)
3. Split () join()
Answer: The former is to cut a string into an array, the latter is to convert an array into a string
Pop () push() unshift() shift()
Answer: Push () tail add pop() tail remove Unshift () header add Shift () header remove
5. What are the compatible writing methods under IE and standards
The answer:
var ev = ev || window.event
document.documentElement.clientWidth || document.body.clientWidth
Var target = ev.srcElement||ev.target
Copy the code
6. The difference between GET and POST for Ajax requests
Answer: One after the URL, one in the virtual carrier get has a size limit (can only submit a small number of parameters) security issues different applications, request data and submit data
7. The difference between call and apply
Object. Call (this,obj1,obj2,obj3) Object. Apply (this,arguments)
8. How do I parse JSON data during Ajax requests
Answer: Use json.parse
9. What is event delegation
Answer: use the principle of event bubble, let their triggered event, let his parent element instead of execution!
10. What are closures, what are their features, and how do they affect pages
A closure is a function that reads the internal variables of other functions so that the function is not collected by the GC and can leak memory if it is used too much
11. How do I prevent events from bubbling
Answer: IE: Prevent ev.cancelBubble = true; The IE ev. StopPropagation ();
12. How do I prevent default events
(1)return false; (2) ev.preventDefault();
13. Add delete replace methods inserted into a contact
The answer:
Create a new node createElement() // Create a concrete element createTextNode() // create a text node
AppendChild () // Add removeChild() // remove replaceChild() // replace insertBefore() // insert
3) Find getElementsByTagName() // by the tag Name getElementsByName() // by the value of the element Name attribute getElementById() // by the element Id, unique
14. Explain how JSONP works and why it is not real Ajax
Answer: Dynamically create script tags, Ajax callback function is the page without refresh request data manipulation
15. Difference between Document Load and Document Ready
Document.onload is executed after the structure and style, external JS, and image have been loaded. Document.ready is executed after the DOM tree has been created.
16. Difference between “==” and “===”
Answer: The former will automatically cast, and then judge whether the latter will not automatically cast, directly to the comparison
17. The difference between a function declaration and a function expression?
In Javscript parser when to load the data in the execution environment, the function declarations and function expression is not alike, the parser will first read the function declarations, and make it available before perform any code (access), as for the function expression, you must wait until the parser performs to its line of code, that would truly be parsed.
18. To understand the scope context and this, look at the following code:
var User = { count: 1, getCount: function() { return this.count; }}; console.log(User.getCount()); // what? var func = User.getCount; console.log(func()); // what? What are the two console outputs? Why is that? Answer: 1 and undefined. Func is executed in the context of the window, so the count attribute is not accessed.Copy the code
19. Look at the following code to give the output.
for(var i = 1; i <= 3; SetTimeout (function(){console.log(I); }, 0); }; Answer: 4, 4, 4. Cause: the Javascript event handler does not run until the thread is idle.Copy the code
20. When a DOM node is clicked, we want to be able to execute a function. What should we do?
box.onlick= function(){}
box.addEventListener(“click”,function(){},false);
21. What is the Javascript event flow model?
“Event bubbling” : Events begin to be accepted by the most concrete element and then propagate up the hierarchy
“Event capture” : Events are received first by the least specific node and then progressively down to the most specific node
“DOM event flow” : three phases: event capture, target, and event bubbling
Look at the following code. What does it output? Explain why.
var a = null; alert(typeof a); Null is a data type that has only one value, which is NULL. Represents a null pointer object, so typeof detection returns "object".Copy the code
23. Check that the string starts with a letter and can be followed by numbers, underscores, or letters. The string is 6 to 30 characters in length
Var/reg = ^ [a zA - Z] \ w {5, 29} $/;Copy the code
24. What are the values of alert in response to the following codes?
<script> var a = 100; function test(){ alert(a); a = 10; Alert (a); alert(a); } test(); alert(a); The correct answer is: 100, 10, 10Copy the code
25. What is the difference between the two javaScript variable ranges?
Global variables: valid within the current page
Local variables: function methods are valid within
26. The difference between null and undefined?
Null is an object representing “none” and is zero when converted to a value; Undefined is a primitive value for “none”, which is NaN when converted to a value.
When the declared variable has not been initialized, the default value of the variable is undefined. Null is used to indicate objects that do not yet exist
Undefined means “missing value”, that is, there should be a value here, but it is not defined yet. Typical usage:
(1) If a variable is declared but not assigned, it is undefined.
(2) When the function is called, the argument that should be provided is not provided, which is equal to undefined.
(3) The object has no assigned attribute. The value of this attribute is undefined.
(4) If the function does not return a value, undefined is returned by default.
Null means “no object”, meaning there should be no value. Typical usage:
(1) as the parameter of the function, indicating that the parameter of the function is not an object.
(2) as the end of the object prototype chain.
27. What exactly does the new operator do?
1. Create an empty object that is referenced by this and inherits the prototype of the function.
Properties and methods are added to the object referenced by this.
3. The newly created object is referenced by this and returns this implicitly.
28. What are the ways of lazy loading of JS?
Defer and Async, create DOM dynamically (create script, insert into DOM, callBack after loading), and load JS asynchronously on demand
29. What are the advantages and disadvantages of Flash and Ajax?
Flash ajax contrast
(1)Flash is suitable for processing multimedia, vector graphics, access to the machine; On CSS, processing text is insufficient and not easy to search.
(2) Ajax for CSS, text support is very good, support search; Insufficient multimedia, vector graphics, machine access.
Common features: no refresh messaging with the server, user offline and online status, DOM manipulationCopy the code
30. Write a function that gets non-line styles
function getStyle(obj,attr) {
if(obj.currentStyle) {
return obj.currentStyle[attr];
}else{
getComputedStyle(obi,false)[attr]
}
}
Copy the code
31. How to obtain all the checkboxes in a page? (No third-party frameworks)
var inputs = document.getElementsByTagName("input"); Var checkboxArray = []; // Initialize an empty array to hold the checkbox object. for(var i=0; i<inputs.length; i++){ var obj = inputs[i]; if(obj.type=='checkbox'){ checkboxArray.push(obj); }}Copy the code
Write a function that clears Spaces before and after strings. (Compatible with all browsers)
String.prototype.trim= function(){
return this.replace(/^\s+/,"").replace(/\s+$/,"");
}
Copy the code
33. There are many features of the javascript language that are different from other programming languages we have been working with. Please give examples
At the heart of the javascript language’s inheritance mechanism is 1 (archetype), rather than the Java language’s class-like inheritance. When the Javascript parsing engine reads the value of an Object property, it looks up 2 (prototype chain). If it does not find the value, the property value is 3 undefined. If the value of the property is eventually found, the result is returned. In contrast to this process, when the javascript parsing engine performs “assign a value to a property of an Object,” it overwrites the value of the property if it exists in the current Object, or assigns the value of the property if the current Object does not itself exist.
34. How are cookies stored on the client
Cookies are text files that servers temporarily store on your computer so they can identify your computer. When you visit a Web site, the Web server sends a small piece of information to your computer, and Cookies record the text or choices you make on the site. The next time you visit the same site, the Web server looks to see if it has any Cookies from the last time it visited the site. If it does, it determines the user based on the contents of the Cookies and sends you specific Web content.
35. How do I get the maximum and minimum values of three javascript numbers?
Math.max(a,b,c); / / Max
Math. Min (a, b, c) / / minimum value
36. Javascript is object-oriented, how to reflect the inheritance relationship of javascript?
Use the Prototype to do this.
37.. form input can be readonly or disable.
Readonly is not editable, but can be selected and copied; Values can be passed to the background disabled cannot be edited, cannot be copied, cannot be selected; Values cannot be passed to the background
38. List the three main data types of javaScript, two compound data types, and two special data types.
Main data types: string, Boolean, number
Compound data types: function, object
Special type: undefined, null
39. How to catch exceptions in a program?
try{
}catch(e){
}finally{
}
Copy the code
40. Ajax principle
Var XHR = new XMLHttpRequest(); Xhr. open('GET', 'example.txt', true); Xhr.send (); Xhr.onreadystatechange =function(){} (1) The readyStatechange event is triggered when the readyState value changes from one value to another. (2) When readyState ==4, it indicates that all response data has been received. (3) When status ==200, the server successfully returns the page and data. (4) If (2) and (3) both satisfy, xhr.responsetext can be used to obtain the content returned by the server.Copy the code
Explain what Json is:
(1)JSON is a lightweight data interchange format.
(2)JSON is language – and platform-independent; JSON parsers and JSON libraries support many different programming languages.
(3)JSON syntax represents three types of values, simple values (string, numeric, Boolean, NULL), array, object
42. What are the commands of the three pop-up message reminders (warning window, confirmation window, information input window) in JS?
alert
confirm
prompt
43. The following code execution results
var uname = 'jack' function change() { alert(uname) // ? var uname = 'lily' alert(uname) //? } change() alert = undefined, lily,Copy the code
44. Browser scrolling distance:
Distance of the viewable area from the top of the page
scrollTop=document.documentElement.scrollTop||document.body.scrollTop
45. Viewable area size:
(1)innerXXX (incompatible with IE)
InnerHeight The height of the viewable area, including the width of the scroll bar
Window. innerWidth Width of the viewable area, including the width of the scroll bar
(2) of the document. The documentElement. ClientXXX compatible (ie)
Document. The documentElement. ClientWidth visual zone width, width does not contain the scroll bar
Document. The documentElement. ClientHeight visual zone height, width does not contain the scroll bar
46. There are several types of nodes. What are they?
Element node: nodeType ===1;
Text node: nodeType ===3;
Attribute node: nodeType ===2;
47. Difference between innerHTML and outerHTML
InnerHTML (the content contained within an element)
OuterHTML (you and the contents of the element)
48. Difference between offsetWidth offsetHeight and clientWidth clientHeight
(1)offsetWidth (Content width +padding width +border width)
(2)offsetHeight (Content height +padding height +border height)
(3)clientWidth (Content width +padding width)
(4)clientHeight (Content height +padding height)
49. Benefits of closures
(1) Want a variable to be permanently stored in memory (not collected by garbage collection)
(2) Avoid pollution of global variables
(3) The existence of private members
(4) Improved security
50. Bubble sort algorithm
Var array = [5, 4, 3, 2, 1]; var temp = 0; for (var i = 0; i <array.length; i++){ for (var j = 0; j <array.length - i; j++){ if (array[j] > array[j + 1]){ temp = array[j + 1]; array[j + 1] = array[j]; array[j] = temp; }}Copy the code
Js implement a function to clone the JSON object in javascript
var oldObject ="sdf"; var newObject = JSON.parse(JSON.stringify(oldObject)); console.log(newObject); Or var a = 'DDDD '; function cp(a){return JSON.parse(JSON.stringify(a))} console.log(cp(a));Copy the code
52. Js implements the lock screen function and unlock function in ajax request or Submit request (interface Loading and elements cannot be clicked during the request, Loading will be eliminated when the request is completed)
function(url, fn) { var obj = new XMLHttpRequest(); Obj. open(‘GET’, url, true); // XMLHttpRequest object is used to exchange data with the server in the background. obj.onreadystatechange = function() { if(obj.readyState == 4 && obj.status == 200||obj.status == 304) {
Load.style. display = "none"} else {alert(" can't click, ha ha ha!" ); }};Copy the code
obj.send(null);
}
53, js implements a function to get the value of the URL parameter
function getQueryString(name) { var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); var r = window.location.search.substr(1).match(reg); if (r ! = null) return unescape(r[2]); return null; }Copy the code
54, Please use js to count the number of occurrences of 0 in 1-10000
new Array(10000).fill('').map((_, index) => index + 1).filter(item => /0/.test(item)).reduce((count, item) => { return count + (String(item).match(/0/g) || []).length}, 0)
Copy the code
55, Write a function that clears Spaces before and after strings. (Compatible with all browsers)
function trim(str) { if (str & typeof str === "string") { return str.replace(/(^s*)|(s*)$/g,""); // Remove before and after whitespace}}Copy the code
56, Dimensional reduction array
Var arr = [[1, 2], [3, 4]]. function Jw(obj){ return Array.prototype.concat.apply([],obj); } Jw(arr);Copy the code
57, parse the URL query parameters into dictionary objects
…
function getQueryObject(url) {
url = url == null ? window.location.href : url;
var search = url.substring(url.lastIndexOf(“?” ) + 1);
var obj = {};
var reg = /([?&=]+)=([?&=]*)/g;
search.replace(reg, function (rs, 2) {
var name = decodeURIComponent(2);
val = String(val);
obj[name] = val;
return rs;
});
return obj;
}
…
Determine the number of occurrences in a string and count the number of occurrences
···
var str = ‘asdfssaaasasasasaa’;
var json = {};
for (var i = 0; i < str.length; i++) { if(! json[str.charAt(i)]){ json[str.charAt(i)] = 1; }else{ json[str.charAt(i)]++; }}; var iMax = 0; var iIndex = ”; for(var i in json){ if(json[i]>iMax){ iMax = json[i]; iIndex = i; }} alert(‘ +iIndex+’ +iIndex+’ +iMax+’); …
Write a method to find the length of a string in bytes;
Var STR = ’22 double yes ‘;
alert(getStrlen(str))
function getStrlen(str){ var json = {len:0}; var re = /[\u4e00-\u9fa5]/; for (var i = 0; i < str.length; i++) { if(re.test(str.charAt(i))){ json[‘len’]++; }}; return json[‘len’]+str.length; }…
Write a method to remove duplicate elements from an array
Var arr = [1,2,3,1,43,12,12,1]; var json = {}; var arr2 = []; for (var i = 0; i < arr.length; i++) { if(! json[arr[i]]){ json[arr[i]] = true; }else{ json[arr[i]] = false; }
if(json[arr[i]]){
arr2.push(arr[i]);
}
Copy the code
};
for (var i = 0; i < arr.length; i++) { if(! aa(arr[i], arr2)){ arr2.push(arr[i]) } }; function aa(obj, arr){ for (var i = 0; i < arr.length; i++) { if(arr[i] == obj) return true; else return false; }; } alert (arr2)…
61. Name three typical applications that use this
Event: such as onclick this-> the object constructor this->new out of the object call/apply changes this
How to deep clone
··· var arr = [1,2,43]; Var json = {6, a: b: 4, c: [1, 2, 3]}. var str = ‘sdfsdf’;
var json2 = clone(json);
alert(json[‘c’]) function clone(obj){ var oNew = new obj.constructor(obj.valueOf()); if(obj.constructor == Object){ for(var i in obj){ oNew[i] = obj[i]; if(typeof(oNew[i]) == ‘object’){ clone(oNew[i]); } } } return oNew; }…
63. How do I detect if a variable is a String in JavaScript? Write the function implementation
··· Typeof (obj) == ‘string’ obj.constructor == string; …
64, the web page to achieve a calculation of how much time is left in the countdown program, requiring real-time dynamic display on the web page “×× year left ×× days ×× hours ×× minutes ×× seconds”
···
var oDate = new Date();
var oYear = oDate.getFullYear();
var oNewDate = new Date();
oNewDate.setFullYear(oYear, 11, 31, 23, 59, 59);
var iTime = oNewDate.getTime()-oDate.getTime();
var iS = iTime/1000; var iM = oNewDate.getMonth()-oDate.getMonth(); Var iDate = iS…
65. Explain what semantic HTML is.
Content uses specific tags that give you an idea of the overall layout of the page
Why is it more effective to use multiple domain names to store website resources?
Make sure that users can access the site as quickly as possible in different regions, and that users can access the site from other sites if their domain name crashes
Name three ways to reduce page load time
1. Compress CSS and JS files; 2. Merge JS and CSS files to reduce HTTP requests; 3
What is FOUC? How do you avoid FOUC?
The CSS file is loaded after the HTML due to the use of @import or the presence of multiple style tags and the CSS file is introduced at the bottom of the page, causing the page to flicker and splutter. Load the CSS file with link and place it inside the head tag
69. What is the role of document types? How many document types do you know?
Affect the browser to compile HTML code rendering HTML2.0 xHtml HTML5
70. What’s the difference between browser standard mode and weird mode?
The box model is interpreted differently
71, closures
If a subfunction can be called externally, all variables connected to that function are saved.
Explain what the Javascript module pattern is and give a practical example.
Js modular MVC (Data layer, presentation layer, Control layer) SeaJS namespace
73. How do you organize your code? Do you use the module pattern, or do you use the classic inheritance approach?
Internal: module mode external: inheritance
How do you optimize your code?
Code reuse avoids global variables (namespaces, closed Spaces, modular MVC..) Split functions to avoid functions with bloated comments
75. Can you explain how inheritance works in JavaScript?
The parent constructor is executed in the child constructor and the methods on this clone parent constructor prototype are changed with Call \apply
Please explain how AJAX works in as much detail as possible.
Create ajax object (XMLHttpRequest/ActiveXObject (Microsoft. XMLHttp)) to judge the data transmission mode (GET/POST) open the link to the open () sends the send () When the Ajax object completes step 4 (onreadyStatechange) and the data is received, the HTTP response status (status) between 200-300 or 304 (cache) executes the callback function
The simplest problem
Var a = 2, b = 3; var c = a+++b; // c = 5 ···
78, Pre-parsing var and function, and prioritizing variables and functions
Function b () {console.log(a); function b () {console.log(a); var a = 10; function a() {}; a = 100; console.log(a); } b();
function c () { console.log(a); function a() {}; var a = 10; a = 100; console.log(a); } c(); (function d (num) { console.log(num); var num = 10; }(100)) (function e (num) { console.log(num); var num = 10; function num () {}; }(100)) (function f (num) { function num () {}; console.log(num); var num =10 console.log(num); } function m () {console.log(a1);} function m () {console.log(a1); // underfined console.log(a2); // underfined console.log(b1); // underfined console.log(b2); // underfined if(false) { function b1 (){}; var a1 = 10; } if(true) { function b2 (){}; var a2 = 10; } console.log(a1); // underfined console.log(a2); // 10 console.log(b1); // underfined console.log(b2); // function } m(); function n() { if(2>1) { arr = 10; brr = 10; let arr; var brr; console.log(arr); console.log(brr); } } n(); // ReferenceErrorCopy the code
…
79. What is the principle of DOM event delegation and what are its advantages and disadvantages
Event delegation principle: Event bubbling mechanism
advantages
1. It can greatly save memory usage and reduce event registration. For example, an UL proxy for all the LI’s click events is a good idea. 2. When a new child object is added, there is no need for event binding, especially for the dynamic content part
disadvantages
Common use of event brokers should be limited to the above requirements; if you use event brokers for all events, event misjudgment may occur. That is, events are bound to events that should not be raised.
80, HTTP cache mechanism, and how to implement from cache in 200 state.
meaning
Definition: Browser Caching is used to speed up browsing. The Browser stores the recently requested document on the user’s disk. When the user requests the page again, the Browser can display the document from the local disk, which speeds up the page viewing.
role
How cache works: 1. Reduce latency, make your site faster, and improve user experience. 2, avoid network congestion, reduce the amount of requests, reduce the output bandwidth.
Realization means
In cache-control, max-age is the main method to implement content Cache. There are three common strategies: the combination of max-age and last-Modified (if-Modified-since), max-age only, max-age and ETag.
For mandatory caching, the server notifies the browser of a cache time, within which the next request is made, the cache will be used directly. For comparison cache, Etag and Last-Modified in the cache information are sent to the server through a request, which is verified by the server. When the 304 status code is returned, the browser directly uses the cache.
A prototype chain inheritance problem
Function A (num) {this.titileName = num; } A.prototype = { fn1: function () {}, fn2: function () {} }Copy the code
This problem focuses on the static property of A that B inherits, and the titleName property of an instance of A does not exist in B’s prototype chain
What is the virtual DOM
Why is React so big? Because it implements a Virtual DOM. What is the virtual DOM for? It starts with the browser itself
As we know, when a browser renders a web page, after loading an HTML document, it parses the document and builds a DOM tree, which is then combined with the CSSOM tree generated by parsing THE CSS to produce the RenderObject tree, a crystallization of love. The RenderObject tree is then rendered into a page (with some optimizations possible, such as the RenderLayer tree). These processes exist in the rendering engine, which is separate from the JavaScript engine (JavaScript core or V8) in the browser, but exposes interfaces for JavaScript to call in order for JavaScript to manipulate DOM structures. Because the two pieces are separate, communication is costly, and the interface provided by JavaScript calls to the DOM does not perform well. Various performance optimization best practices are also aimed at minimizing DOM operations.
What does the virtual DOM do? It implements the DOM tree (roughly) directly in JavaScript. Instead of directly generating the DOM, the COMPONENT’s HTML structure maps to a virtual JavaScript DOM. React implements a diff algorithm on the virtual DOM to find minimal changes and then writes those changes into the actual DOM. This virtual DOM exists in the form of JS structure, and the computational performance is better, and the performance is greatly improved because the number of actual DOM operations is reduced
What are the basic data types and reference types of JS? Write a getType that returns the corresponding type
1. Basic data types (non-separable) : Undefined, Null, Boolean, Number, String 2. Reference datatypes: Object (Array, Date, RegExp, Function) ES6 basic datatypes: Object (Array, Date, RegExp, Function) ES6 basic datatypes: ES6 basic datatypes
function gettype(nm){
return Object.prototype.toString.call(nm);
}
Copy the code
84, What is the dom selector priority and how to calculate the weight value (an old problem)
Id 0100 3. Class selector, pseudo-class selector, attribute selector [type=”text”] 0010 4. Label selector, pseudo-element selector (::first-line) 0001 5. Wildcard *, child selector, adjacent selector 0000
85. What is the principle of VUE two-way data binding
First, the Object’s bidirectional data binding object.defineProperty (target, key, Decription), which sets get and set properties (note that get and set in description cannot coexist with description properties). Arrays are implemented differently from objects. At the same time, the observer mode is used to update wather, user data and view
86. How does React compare to Vue
1. Component level, Web Component and Virtual DOM 2 data binding (VUE bidirectional, React unidirectional), etc. React does not work. 4 vue can watch a data item. React does not work. 5 Vue is easier to develop scenarios because of the direct provided, especially the preset directive. React does not have 6 Too long life cycle function names directive
What do you do if you are developing git and a bug needs to be fixed in another branch
Git stash // Save this change to the staging area (in case of an emergency branch switch) git stash pop // Remove all contents of the staging areaCopy the code
What kinds of web layout, what is the difference
Static layout: the layout of a web page is the same as the layout of the code that was written at the time, regardless of the size of the browser. Adaptive layout: when you see a page, the position of elements changes but the size does not; Streaming layout: When you see a page, the size of the elements changes but the position does not — this leads to elements not appearing properly if the screen is too big or too small. Adaptive layout: Each screen resolution has a layout style that changes position and size.
89. Execute the following code
var a = {}; var b = {key: 'b'}; var c = {key: 'c'}; Var d = [3 and 6]; a[b] = 123; a[c] = 345; a[d] = 333; console.log(a[b]); // 345 console.log(a[c]); // 345 console.log(a[d]); / / 333Copy the code
In 90,
var R = (function() { var u = {a:1,b:2}; var r = { fn: function(k) { return u[k]; } } return r; } ()); R.fn('a'); / / 1Copy the code
How do I get u from an anonymous function in this code
[0,1,2,3,4,5……..99] [0,1,2,3,4,5……..99]
var arr = new Array(100); // method 1 [...arr.keys()]; Array.from(arr.keys()); Array.from({length: 100}); Var arr1 = new Array(101); var str = arr1.join('1,'); str = str.replace(/(1\,)/g, function ($0, $1, index) { var start = '' + Math.ceil(index/2); if(index < str.length - 2) { start += ',' } return start; }); return str.split(','); / / methods five (functional, reference network) function reduce (arr, val) {if (Object. The prototype. ToString. Apply (val)) {return; } if(val >= 100) { return arr; } arr.push(val); return reduce(arr, val+1); } var res = reduce([], 0)Copy the code
92, the following statement to execute the result output
var a = function (val, index) { console.log(index); return { fn: function (name) { return a(name, val); } } } var b = a(0); // underfined b.fn(1); // 0 b.fn(2); // 0 b.fn(3); / / 0Copy the code
93, the popular science
- Answer: No, the root of a DOM node is HTML (including head and body). Body is divided into two groups.)
Answer: The offsetParent property returns a reference to an object that is closest (in the containment hierarchy) to the element that called offsetParent and that has been CSS positioned. If the container element is not CSS positioned, the offsetParent attribute takes the value of the root element (HTML element in standards-compliant mode; A reference to the body element in weird rendering mode. The offsetParent property returns null when style.display of the container element is set to “None”.
- Answer: ‘1,3,5’ calls the toString method to generate the string
The parent element of the li tag can be li, and the parent element can also be li
94, JSONP principle, how is jquery implemented, what are the advantages and disadvantages of this implementation
The principle of
Under the same origin policy; Pages under a server cannot get data outside of that server; While the core of Ajax in Jquery is fetching out-of-page content via XmlHttpRequest, the core of JSONP is dynamic addition
$. Ajax ({url: 'http://192.168.1.114/yii/demos/test.php', / / different domain type: 'GET', / / the json model is legal only GET data: {' action ': 'Aaron'}, dataType: 'jsonp', // dataType jsonp: 'backfunc', / / the specified callback function name, consistent with the server receives, and returned back jquery will be converted into internal http://192.168.1.114/yii/demos/test.php?}) Backfunc = jQuery2030038573939353227615_1402643146875 & action = Aaron and dynamic loading < script Type = "text/javascript" SRC = "http://192.168.1.114/yii/demos/test.php? Backfunc => The back end then performs backfunc(pass arguments), sending the data as arguments.Copy the code
Jsonp is implemented dynamically in jquery source code
Which of the seven layers does HTTP belong to, and what is the next layer
Seven layers: physical layer, data link layer, network layer, transport layer, session layer, presentation layer, and application layer TCP belongs to the transport layer. HTTP belongs to the application layer. The presentation layer
What js garbage collection knows, which v8 engine uses
Js two recycling mechanisms
1 Mark and sweep 2 Reference Counting
Javascript with the V8 engine
The pros and cons of garbage collection
Benefits: Greatly simplifies application memory management code, reduces application load, and reduces memory leaks due to long running.
The bad: Automatic recycling means programmers can’t control memory. There is no excuse to expose garbage collection in ECMAScript, there is no way to force garbage collection, and there is no way to interfere with memory management.
V8 Automatic garbage collection algorithm segmentfault.com/a/11…
When was the scope created?
Page load –> create window global object, and generate global scope –> generate execution context, pre-parse variables (variable promotion), generate global variable object; $scope
What is the principle of websocket long connection
meaning
Websocket is a persistent protocol, as opposed to HTTP, which is not persistent.
The principle of
Similar to long round loop long connection; Send a request; A steady stream of information
28. What the HTTP cache knows
blog.csdn.net/yzf91321…
Talk about the event loop
The Execution context function calls the call stack and queue promises
zhuanlan.zhihu.com/p/…
Understand Web security? What are they and how to prevent them
1.XSS, for cross-site script injection
Manual attack: write injection script, such as "/><script>alert(document.cookie()); </script><! -- Manually test all possible fields on the target site such as input, textarea, etc. Automatic attacks use tools to scan all the pages of the target website and automatically test the injection scripts written, such as: Burpsuite, etc. Set sensitive information such as cookies to httpOnly, disallow Javascript to obtain 2\. Strictly checks all input, especially on the server side, to filter out any illegal input, such as the mobile phone number must be a number, usually using the regular expression 3\. Clean and filter out unnecessary HTML tags such as <iframe>, Alt,<script>, etc. 4\. Clean and filter out unnecessary Javascript event tags, such as onclick, onfocus, etc. 5\. To escape special characters such as single quotes, double quotes, Angle brackets, etc., you can use htmlenCode encoding or filter out these special characters 6\. Set your browser's security Settings to guard against typical XSS injectionsCopy the code
2. SQL injection
Attack method: write malicious string, such as' or 1=1-- etc., manually test the target website on all the places involving database operations defense method: 1\. Disallow target websites to access the database using dynamic concatenation strings. 2. Reduce unnecessary database error messages. 4\. Purify and filter out unnecessary SQL reserved words, such as: where, or, exec, etc. 5\. To escape special characters such as single quotes, top quotes, Angle brackets, etc., you can use HTmlencode to encode or filter out these special charactersCopy the code
CSRF, which stands for cross-site request forgery
Is the attacker impersonates the name of the user, to send a request to the target site defense method: 1\. Hashing cookies on the client side, and hash authentication on the server side 2\. To submit requests, fill in verification code 3\. Use One-time Tokens to create different pseudo-random values for different formsCopy the code
101, sessionStorage and localstorage can be obtained across domains? For example, can I get the value I set at www.baidu.com at m.baidu.com? why
LocalStorage, like cookies, is cross-domain restricted and affected by document.domain
102. When will localStorage expire when it cannot be manually deleted
Unless cleared, permanently save clear() to make it clear that sessionStorage is only valid for the current session and is cleared after closing the page or browser
103, What fields can cookies be set to? Can I set.com
You can do this by setting domin
Do you think the login state can be saved in sessionStorage or localStorage or cookie or do you know which way, where it exists? Why is it kept there
105. What is the nature of the flux -> redux -> MOBx change
Storage structure manipulates objects to observable function vs object-oriented zhuanlan.zhihu.com/p/…
106. Load route on Demand How to load the chunk file? In other words, how does the browser know when to load the chunk, and how does WebPack recognize multiple chunks that have been hashed
What’s the difference between GET and POST? Can get pass data through body
To put the data inside the body, you must POST it, which is restricted by HTTP.
108. Fixed width on the right and adaptive on the left
The first:
<style>
body{
display: flex;
}
.left{
background-color: rebeccapurple;
height: 200px;
flex: 1;
}
.right{
background-color: red;
height: 200px;
width: 100px;
}
</style>
<body>
<div class="left"></div>
<div class="right"></div>
</body>
Copy the code
The second,
<style>
div {
height: 200px;
}
.left {
float: right;
width: 200px;
background-color: rebeccapurple;
}
.right {
margin-right: 200px;
background-color: red;
}
</style>
<body>
<div class="left"></div>
<div class="right"></div>
</body>
Copy the code
109, Horizontal and vertical center
The first kind of
#container{
position:relative;
}
#center{
width:100px;
height:100px;
position:absolute;
top:50%;
left:50%;
transform: translate(-50%,-50%);
}
Copy the code
The second,
#container{
position:relative;
}
#center{
width:100px;
height:100px;
position:absolute;
top:50%;
left:50%;
margin:-50px 0 0 -50px;
}
Copy the code
The third kind of
#container{
position:relative;
}
#center{
position:absolute;
margin:auto;
top:0;
bottom:0;
left:0;
right:0;
}
Copy the code
A fourth flex
#container{
display:flex;
justify-content:center;
align-items: center;
}
Copy the code
109. The differences between the four kinds of positioning
Static is the default value. Relative position Is offset from its original position. Absolute Is still in the standard document flow. There is a positioned ancestor element relative to the most recently positioned ancestor element, which is used as a reference. If there is no located ancestor element, the body element is used as the offset reference, completely out of the standard document flow. Fixed Positioned elements are positioned relative to the window, which means that even as the page scrolls, it will remain in the same position. A fixed location element does not retain the space it should have on the page.
110, encapsulate a function that takes the timer time. Then executes the callback function.
function sleep (time) {
return new Promise((resolve) => setTimeout(resolve, time));
}
Copy the code
One line of code for array deduplicating?
[... new Set ([1,2,3,1, 'a', 1, 'a'])]Copy the code
112, Use addEventListener to click on li to pop up the content, and add li dynamically
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
var ulNode = document.getElementById("ul");
ulNode.addEventListener('click', function (e) {
if (e.target && e.target.nodeName.toUpperCase() == "LI") {
alert(e.target.innerHTML);
}
}, false);
Copy the code
113, How to determine whether two objects are equal
JSON.stringify(obj)==JSON.stringify(obj); //trueCopy the code
114, How to redirect a Vue router to a router?
router.go(1)
router.push('/')
Copy the code
115, What is the difference between Vue router redirect and location.href?
Router is a hash to change location.href is a page jump to refresh the page
116. Rearrange and redraw
Part of the render tree (or the entire render tree) needs to be re-analyzed and the node sizes recalculated. This is called rearrangement. Note that there is at least one rearrange-initialization page layout. Parts of the screen need to be updated when the node’s geometry changes or when the style changes, such as changing the element’s background color. Such updates are called redraws.
117. What circumstances trigger rearrangement and redraw
Add, delete, and update DOM nodes by using display: None to hide a DOM node – triggering rearrangement and redrawing via visibility: Hidden To hide a DOM node – Only trigger redraw, since there are no geometric changes to move or animate the DOM node in the page. Add a style sheet, adjust the style properties user behavior, such as resize the window, change font size, or scroll.
118, Js bind implementation mechanism? Hand write a bind method?
function bind(fn, context){ return function (){ return fn.apply(context, arguments); PursuitTom, pursuitTom, pursuitTom, pursuitTom, pursuitTom, pursuitTom, pursuitTom, pursuitTom Array.prototype.slice.call(arguments, 1); var _this = this; return function () { var thisArgs = [].slice.call(arguments); return _this.apply(context, args.concat(thisArgs)) }; Function. Prototype. Bind = Function (context,... res) { let self = this return function(... arg) { return self.apply(context, [...res,...arg]) } }Copy the code
119. Multiple functions
var a = (function(){return '1'; }, function(){return 1; }) (); console.log(typeof a); //numberCopy the code
120, prototype, object.getProtoTypeof ()
Function f(){} f.__proto__ === object.getPrototypeof (f); //true f.prototype === Object.getPrototypeOf(f); //falseCopy the code
121. Jump before and after browsing records (not tested yet)
<a href="javascript:history.go(-1)">backward</a>
<a href="javascript:history.go(1)">forward</a>
Copy the code
122. SetTimeout and setInterval
The function is added to the execution queue after a certain period of time, execution time = delay time + previous function code execution time + function execution time. The latter is repeated at certain intervals, regardless of whether the previous execution is completed or not, for precise execution of repeated operations that do not affect each other. If you want to control the sequential execution, it is best to use setTimeout to simulate setInterval
var time = 400, times = 0, max = 10;
function func(){
times++;
if(times < max){
//code here
setTimeout(func, time);
} else {
console.log("finished");
}
}
setTimeout(func, time);
Copy the code
123. Judge that multiple images have been loaded
Note: JqueryObject.ready () can only be used to determine when the DOM structure is loaded. Method 1:
var counter = 0;
var queryInterval = 30; //ms
var pics = document.getElementsByClassName("pics");
function singleQuery(i){
if(pics[i].complete){
counter++;
console.log(i + " is loaded");
} else {
setTimeout(singleQuery, queryInterval, i);
}
}
function allQuery(callback){
if(counter < pics.length){
console.log("current number of loaded pics: " + counter);
setTimeout(allQuery, queryInterval, callback);
} else {
console.log("All pics are loaded.");
callback();
}
}
for(var i = 0; i < pics.length; i++){
setTimeout(singleQuery, queryInterval, i);
}
setTimeout(allQuery, queryInterval, callback);
Copy the code
SetTimeout is mainly used to simulate polling, and the judgment method is the complete attribute (Boolean value) of THE IMG tag DOM. The disadvantage is that there are too many timers.
Method 2:
var counter = 0, queryInterval = 50;
var pics = document.getElementsByClassName("pics");
for(var i = 0; i < pics.length; i++){
pics[i].onload = function(){
counter++;
console.log(this.id + " is loaded");
}
}
function queryPictures(callback){
if(counter < pics.length){
console.log("current number of loaded pics: " + counter);
setTimeout(queryPictures, queryInterval, callback);
} else {
console.log("All pics are loaded");
callback();
}
}
setTimeout(queryPictures, queryInterval, callback);
Copy the code
Use onload to bind the callback after the image is loaded successfully, and determine whether the loading is complete through the counter.
124, CSS margin overlap problem
The vertical margin of block elements is strange and overlaps. If the display is block, there are three kinds of situations: outer space are positive, will choose the largest vertical direction from the outside as a is a negative interval, interval = positive – negative | | two negative, spacing = 0 and absolute value of the largest that set the display: Inline-block boxes do not have margin overlap and position: absolute does not appear.
CSS selector priority && CSS selector efficiency
ID > Class > Tag > Neighbor > child selector > descendant selector > * > Properties > Pseudo class
object.propertyIsEnumerable(xxx)
Check whether the object has a XXX attribute and can pass the for in enumeration, for example, the length of the Array object is not enumerable
126, Judge the array
function isArray(arr){
return Object.prototype.toString.call(arr) === '[Object Array]';
}
Copy the code
127, Git fetch && git pull
Git pull automatically completes the latest remote version of the fetch, and merges git fetch with the local branch
128, WebSocket
HTML5 brings new protocols that establish connections through HTTP-like requests. The main purpose is to get push from the server. The old approach might be to use long polling (that is, waiting for data without breaking the connection) or Ajax polling (sending requests at regular intervals, establishing a connection, and asking if there is new data). The downside of both approaches is the blocking of long polls and redundant connections for Ajax polling. WebSocket is similar in design to a callback. After sending a request to upgrade the server protocol and receiving a confirmation message, the server will actively push new information/data to the client, and an HTTP handshake is required to establish a persistent connection
129. Cross-domain correlation
If the protocol, domain name, or port is different, the domain is regarded as different. (Domain names and their corresponding IP addresses are also cross-domain.)
1.CORS: Cross-Origin Resource Sharing
Based on the cross-domain supported by the server, the server sets the access-Control-Allow-Origin response header, and the browser allows cross-domain
2. Set the domain
Can be set from subdomain to primary domain, such as a.b.c.com — >b.c.com — >c.com. Two pages primary domain is the same) using the frameElement contentWindow. Document. The domain Settings page frame of primary domain, the document. The domain Settings page to the primary domain, and then can retrieve data from the dom to each other. The disadvantage is that it can only be used for interactions between different subdomains.
3. For example, the IMG tag with the SRC attribute sends an HTTP request every time the SRC attribute is changed.
var img = new Image();
img.onload = function(){
//code here
};
img.onerror = function(){
//code here
};
img.src="http://server.com/data?query=3";
Copy the code
The downside is that you can only use GET requests, not data, usually for submitting statistics and so on. Script, link, and iframe only initiate requests when they are added to the DOM
4.HTML5 postMessage
Support IE8+ and mainstream browsers, writing is also simple..
//source: http://test.org:4000 //get the window object of target origin var win = window.open("http://target.com"); //or this, when a frame is used var win = document.getElementById("targetId").contentWindow; win.postMessage("data here", "http://target.com/rest"); //target: http://target.com/tiny function handleMessage(event){ if(event.orgin! ="http://test.org:4000") return; var data = event.data; //code here //event.source is window.opener event.source.postMessage("response data here", event.origin); } window.addEventListener("message", handleMessage, false);Copy the code
5.window.name
Even after multiple layers of iframes are opened on a page, the window.name property value is the same in each iframe, which is used as a data transfer tool. However, due to cross-domain constraints, window.name data in another frame cannot be obtained, so a local proxy (proxy.html) is used:
6. jsonp
The prevailing cross-domain approach calls scripts from other domains to get data, provided that the other domain knows the name of the callback function, which can be sent to the target domain by request. Write jSONP in jQuery
$.getJSON("http://target.com/data?callback=callbackFunctionName", function(data){});
Copy the code
$.getjson converts the responseText to JSON. If the URL has a callback parameter, the data is retrieved as a script tag.
130. Closures are relevant
What is a closure
Closures are functions that have access to variables in the scope of another function
How do I create closures
Use functions nested inside functions
function fn() { for (var i = 0; i < 2; i++) { (function () { var variate = i; SetTimeout (function () {console.log("setTimeout :"+variate); }, 1000); }) (); // closure, execute function immediately, anonymous function} console.log(I); //2 console.log(variate); //variate is not defined } fn();Copy the code
Why closures
- Because access to external active objects is maintained inside the closure, external variables cannot access the inside directly, avoiding global contamination;
- Can be used as a private member, make up for the shortcomings of object-oriented programming due to JS syntax;
- You can store a variable you want in memory for a long time.
Disadvantages of closures
- This can lead to excessive memory usage because closures carry their own function scope
- Closures can only get the last value of the enclosing function
See segmentfault.com/a/11…
131, a: Active mobile terminal implementation
Sometimes simple button click interactions can be implemented with CSS pseudo-classes; Must be clicked to change color; Release recovery; IOS mobile phones will appear pseudo class invalid situation; On iOS mobile devices, you need to bind a TouchStart event to the button element or body/ HTML to activate :active state.
document.body.addEventListener('touchstart', function () { //... });Copy the code
132. Ios sliders are stuck
-webkit-overflow-scrolling:touch may show scrolling if IOS is low; Attempt overflow resolution
133. Differences between forEach and map
The same
- It’s a loop over each term in the set
- The forEach and map methods support three parameters forEach anonymous function executed: item, index, and arr.
- This in anonymous functions refers to the window
- You can only iterate over groups of numbers
- Both have compatibility issues
The difference between
- Map is faster than foreach
- Map will return a new array without affecting the original array,foreach will not generate a new array,
- Map can be chained because it returns an array. Foreach cannot
134. Shallow and deep copies
The first parameter of jquery.extend can be a Boolean value that is used to set the depth copy
jQuery.extend(true, { a : { a : "a" } }, { a : { b : "b" } } );
jQuery.extend( { a : { a : "a" } }, { a : { b : "b" } } );
Copy the code
The simplest deep copy
aa = JSON.parse( JSON.stringify(a) )
Copy the code
Shallow copy -> copies the memory address of one object to another. Deep copy -> implementation principle, first create a new empty object, a new memory open up a piece of address, the copied object all enumerable (note the enumerable object) attribute method one by one copy over, pay attention to use recursive copy of all attributes and methods in the child object, until the child….. Property is a basic data type. To sum up, deep copy understands two points, 1, new open memory address, 2, recursive root copy.
135. Merge margins
Margin merging means that when two vertical margins meet, they form a margin. The height of the merged margins is equal to the greater of the two merged margins.
136. The advantages and disadvantages of JS loading position are different
HTML files are executed from top to bottom, but the order in which CSS is introduced is different from that of javascript. When CSS is introduced, the program is still executed down, while the program is executed to
But you can’t put all the scripts after the body, because some page effects require dynamic loading of javascript scripts in advance. So these scripts should come first.
Second, you can’t place JJS that need to access the DOM element before the body, because dom generation hasn’t started yet, so JJS that access the DOM element before the body will fail or be invalid
Page effect implementation class js should be placed before body, action, interaction, event-driven, and JS that need access to DOM properties can be placed after body
Author: O O ant link: www.jianshu.com/p/f1f39d5b2… The copyright of the book belongs to the author. Commercial reprint please contact the author for authorization, non-commercial reprint please indicate the source.