“Like it before you read it, make it a good habit.” All from (19 years) sophomore to get the offer process don’t want to see nonsense big man directly skip to see dry goods (super heart JS) in addition to the nonsense of the preface, the other are full of dry goods collection always have a useful place to collect not easy to pay attention to and praise encourage me to leave your valuable suggestions in the comments section ~
preface
When I first entered college, I played games and went out every day just like my classmates, but I didn’t think about the future. In my sophomore year, I experienced many things before I realized that I couldn’t do that. I felt sorry for my parents and myself for not doing my homework every day, and I couldn’t see the future at all.
Because I was a class, the first half of the sophomore year in the dormitory fierce fill the front three swordsmen, but the temptation of the dormitory is too big, a roommate on the number! I turned off the computer timi immediately, which made me think that I had not studied yet when playing the game. When I was studying, I wanted to play the game with my roommate, and I found that I was very miserable and did not enjoy the game and did not calm down in study. Began to and other dormitory students to the library closed!
Out of the society, I found that the days in the library are the time when I study the most efficiently! I went to the library with my computer after dinner after class every day until the library closed! When the library opened at eight o ‘clock on weekends, we would get up at 7:30 in the morning and wait for the administrator to open the door after breakfast. After lunch, we would lie down on the library table for a while to continue our study until evening. In the second half of sophomore year, except sleeping in the dormitory, we spent all our time in the classroom and library!
In the middle of the second semester of my sophomore year, I began to prepare for the interview. I scanned the interview questions for half an hour to an hour before studying every day. We interviewed each other half an hour before the library closed, which lasted for a month. At that time, I was very confident that I did not want to apply for the university recruitment, because there were many factories and sales in the school-enterprise cooperation, and several outsourcing companies didn’t suit me, so we prepared for the social recruitment. Yes, some seniors have told me how difficult it is for inexperienced junior college students to recruit from the agency, but I still want to try after all my efforts these days, and I am not willing to go to the outsourcing company of the school recruitment.
I say so much is not to complain, who let us go to school before not good, failed to take an examination of a better university, before stealing lazy sooner or later will have to return
How desperate I was when I contacted 300 and heard nothing! So listen to the classmate’s advice began to cast a year’s post, during the period has also been brush preparation, while the interview while checking the gaps, really useful! With that said, I conclude two months of crazy interviews! (There may be omissions, it is a summary made after work)
html/css
-
CSS box model
Basic concepts of CSS box model?
- Margin, border, padding, content. In web pages, the space occupied by an element is composed of several parts, including content, padding, border and margin. In the space occupied by these four sections, some parts can display the corresponding content, while some parts are only used to separate adjacent areas. Together, the four sections make up the box model of elements in CSS.
- Classification: Standard model, IE model
The difference between the standard model and IE model: calculate the height and width of the difference, how different, how is the height and width calculated?
- The standard model
Div width = content width +border width +padding width // box-sizing:content-box; /* Set the standard box */Copy the code
- Weird model | IE model
Div width = content width + width +padding width // box-sizing:border-box; / * * / IE modelCopy the code
-
BFC (Margin Overlap solution)
Basic concepts of BFC?
Block Formatting Context (BFC) IFC(CSS2.1) GFC(CSS3):GridLayout Formating Contexts, FFC(CSS3):Flex Formatting Context, adaptive Formatting ContextCopy the code
BFC principles/BFC rendering rules?
2. The region of the BFC does not overlap with the box of the floating element (which can be used to clear the float). 3. The BFC is a separate element. When calculating the height of the BFC, the floating element is also involved in the calculation.Copy the code
How do I create a BFC?
1.float2, The value of position is not static(default),relative, Display: inline-block, flex, inline-flex, table-cell,table-caption; overflow: visible; Overflow is auto,hidden, scroll; 5. Use fieldSet elements (HTML elements that surround form elements)Copy the code
What are the BFC application scenarios?
1. BFC vertical margin overlap 2. BFC does notfloatOverlap 3. Clear float: when the child element is a float element, the float element of the child element will also participate in the height calculation of the parent element when the outer element is set to BFC.Copy the code
-
CSS float
How does the CSS float?
A floating box can be moved left and right until its outer edge encounters an edge containing the box or another floating box.Copy the code
Floating elements cause problems?
The height of the parent element cannot be split, affecting elements at the same level as the parent element. 2. Non-floating elements (inline elements) at the same level as the floating element will followCopy the code
How does the CSS clear floating?
1. Add an empty label to all floating labels using an empty label. Define CSS clear:both. But this method adds a meaningless label. Set the parent element to a BFC element. Use after to clear float. This method only works with non-IE browsers. This method must set height:0 for the pseudo object that needs to clear the floating element, otherwise the element will be several pixels higher than the actual element.#parent:after{
content:".";
height:0;
visibility:hidden;
display:block;
clear:both;
}
Copy the code
-
CSS Classic Layout
Three-column layout: 300px left and right, adaptive in the middle?
- Float float
<style> html * { padding:0; margin:0; } .layout{ margin-top:20px; } .layout article div{ min-height:100px; } </style> </head> <body> <! Float solution --> <section class="layout float">
<style media="screen">
.layout.float .left{
float:left;
width:300px;
background:red;
}
.layout.float .right{
float:right; width:300px; background:blue; }.layout.float. Center {/* Block elements automatically spread */ background:yellow; } </style> <article class="left-right-center">
<div class="left"></div>
<div class="right"></div>
<div class="center"> < H1 > Floating solution </ H1 > 1. This is the middle part of the three-blue layout 2. This is the middle part of the three-blue layout </div> </article> </section>Copy the code
- Absolute position: Absolute
<! -- Absolute positioning solutions --> <section class="layout absolute">
<style>
.layout.absolute .left-center-right>div{
position:absolute;
}
.layout.absolute .left{
left:0;
width:300px;
background:red;
}
.layout.absolute .center{
left:300px;
right:300px;
background:yellow;
}
.layout.absolute .right{
right:0;
width:300px;
background:blue;
}
</style>
<article class="left-center-right">
<div class="left"></div>
<div class="center"> < H2 > Absolute positioning solution </ H2 > 1. This is the middle part of the three-blue layout 2. This is the middle part of the tri-blue layout </div> <div class="right"></div>
</article>
</section>
Copy the code
- Flex layout
<! -- Flexbox Solution --> <section class="layout flexbox"> <style> .layout.flexbox{ margin-top:140px; } .layout.flexbox .left-center-right{ display:flex; } .layout.flexbox .left{ width:300px; background:red; } .layout.flexbox .center{ flex:1; /* Background :yellow; } .layout.flexbox .right{ width:300px; background:blue; } </style> <article class="left-center-right">
<div class="left"></div>
<div class="center"> < H2 > Flexbox solution </ H2 > 1. This is the middle part of the three-blue layout 2. This is the middle part of the tri-blue layout </div> <div class="right"></div>
</article>
</section>
Copy the code
- Table layout table-cell
<! Table layout solution --> <section class="layout table">
<style>
.layout.table .left-center-right{
width:100%;
display:table;
height:100px;
}
.layout.table .left-center-right>div{
display:table-cell;
}
.layout.table .left{
width:300px;
background:red;
}
.layout.table .center{
background:yellow;
}
.layout.table .right{
width:300px;
background:blue;
}
</style>
<article class="left-center-right">
<div class="left"></div>
<div class="center"> < H2 > Table layout solution </ H2 > 1. This is the middle part of the three-blue layout 2. This is the middle part of the tri-blue layout </div> <div class="right"></div>
</article>
</article>
</section>
Copy the code
- Grid layout
<! -- Grid layout solution --> <section class="layout grid">
<style media="screen">
.layout.grid .left-center-right{
display:grid;
width:100%;
grid-template-rows:100px;
grid-template-columns:300px auto 300px;
}
.layout.grid .left{
background:red;
}
.layout.grid .center{
background:yellow;
}
.layout.grid .right{
background:blue;
}
</style>
<article class="left-center-right">
<div class="left"></div>
<div class="center"> < H2 > Grid layout solution </ H2 > 1. This is the middle part of the three-blue layout 2. This is the middle part of the tri-blue layout </div> <div class="right"></div>
</article>
</section>
Copy the code
- Extend the advantages and disadvantages of these 5 schemes ① floating: clear floating, compatibility is better. ② Absolute positioning: fast, layout has been out of the document flow, resulting in the following elements also out of the document flow, poor usability. Flex layout solves the disadvantages of floating and absolute positioning, and mobile compatibility is basically already supported. (4) the form layout: form the layout of the compatibility is very good (5) the grid layout: new If “known” away, middle content highly open, need about height also automatically open, what kind of plan is still suitable for (1) can flex, table (2) on the left side of the flex covered, so the display on the right side, there is no shade, will be displayed in the left. Create the landing
- Three column layout (1) left and right width fixed, adaptive in the middle (2) up and down height fixed, adaptive in the middle.
- Two column layout ① left width is fixed, right adaptive ② right width is fixed, left adaptive ③ upper height is fixed, adaptive ④ lower height is fixed, upper adaptive
Holy Grail layout?
- The core of the Holy Grail layout is that the left, center, and right columns float with a float and then adjust with a negative margin.
- The.left,.right margin-left is made so that.main.left. Right is on the same line.
- The padding-left,padding-right,.left position and left of the. Container, and the position and left of the right are used to prevent text from being obscured.
<style>
.main{
float:left;
width:100%;
}
.content{
height:200px;
margin-left:100px;
margin-right:200px;
background-color:green;
}
.main::after{
display:block;
content: ' ';
font-size: 0;
height:0;
clear: both;
zoom:1;
}
.left{
float:left; width:100px; height:200px; margin-left:-100%; /* background-color:red; } .right{float:left; width:200px; height:200px; margin-left:-200px; /* background-color:yellow; } </style> </head> <body> <div class="main">
<div class="content"></div>
</div>
<div class="left"></div>
<div class="right"></div>
Copy the code
-
CSS compatibility
What are some common CSS compatibility issues? How is it solved?
This is all IE8 and previous versions will encounter CSS compatibility issues. The general picture is transparent, rounded corners, font size, the new CSS3 style. ASuncat: Such old browsers will eventually be abandoned by the market and not spend time on them.Copy the code
-
css hack
What is a CSS hack?
The process of writing CSS for different browsers or versions of browsers is called a CSS hackCopy the code
CSS hack classification? 3 kinds: conditional hack, attribute level hack, selector hack.
// 1, conditional <! - [ifIE]> <style> .test{color:red; } </style> <! [endif]-->Copy the code
// 2, attribute hack (class internal hack). Test {color:# 090\9; /*For IE8*/
*color:#f00; /*For IE7 and earlier*/
_color:#ff0; /*For IE6 and earlier*/
}
Copy the code
// 3, the selector is hack (selector attribute prefix method) * HTM. Test {color:#0f90; } /*For IE6 and earlier*/
* + html .test{color:#ff0; } /*For IE7*/
Copy the code
CSS hack writing order?
CSS hack writing sequence is generally defined in the first place with a wide range of CSS that can be easily identified.Copy the code
-
Basic HTML and CSS
What’s the difference between link and @import?
1. Dependency differences: Link is an HTML tag, while @import is provided by CSS. 2. Load order difference: When the page is loaded, link is loaded at the same time, while the CSS referenced by @import waits until the page is loaded. 3, compatibility difference: import can only be identified above IE5, and link is AN HTML tag, no compatibility problem. 4, DOM operability difference: you can manipulate DOM through JS, insert link tag to change the style; Because DOM methods are document-based, you cannot use @import to insert styles. If the same style already exists, the style introduced by @import will be overlapped by the style of the CSS file itself, giving the intuitive effect that the link style weight is higher than the @import style weight. (aSuncat: In a nutshell, link and @import, whichever comes after, the style is applied, and the later style overwrites the previous style.)Copy the code
How to understand tag semantics and what are its benefits?
Semantic elements clearly describe their meaning to browsers and developers. 2, benefits: (1) HTML structure is clear, code readability is good. (2) conducive to SEO, search engines according to the label to determine the context and the weight of each keyword. (3) Barrier-free reading, style loss can make the page show a clear structure. (4) It is convenient for other devices to parse, such as blind readers to render web pages according to semantics. (5) It is convenient for team maintenance and development, more readable semantics, better code maintenance, and more harmonious relationship with CSS3.Copy the code
What are the selectors of CSS, how are their priorities calculated, and which properties can be inherited?
- CSS selector type
Class selector:.class; id selector:.class#id7, group selector: div, p 8, adjacent sibling selector: div +p 9, pseudo-class selector: : Link :visited: Active: Hover: Focus :first-child :first-letter :first-line:before :after :lang(language) [attribute] [attribute=value] [attribute~=value] [attribute|=value]Copy the code
- Priority calculation
! Word-wrap: break-word; word-wrap: break-word; word-wrap: break-word; word-wrap: break-word; word-wrap: break-word; word-wrap: break-word; word-wrap: break-word; word-wrap: break-word; word-wrap: break-word; ① Font series attributes: Font, font-family, font-size, font-style, font-variant, font-weight, font-stretch, font-size-adjust < span style = "max-width: 100%; clear: both; min-height: 1em; Font-size: 16px! Important; font-weight: normal; font-weight: normal; font-weight: normal; font-weight: normal; Vertical-align, text-decoration, text-shadow, Unicode-bidi 3, box model attributes: border, padding, margin, width, height 4, background attributes: Background 5. Location attributes:float7, Outline style attribute: outlien-style 8, page style attribute: size 9, sound style attribute: pause-beforeCopy the code
What are some examples of inline elements and block-level elements?
Inline elements: the span, a, var, em, input, img, img, textarea, var, em, strong, select, lable block-level tags: div, p, h1, h3, ul, ol, dl, li, dd and dt, table, td, trCopy the code
Pseudo classes and pseudo elements?
Pseudotype: :active :focus :hover :link :visited :first-child pseudoelement: : Before: After :first-letter :first-lineCopy the code
What’s the difference between SVG and Canvas?
1. New drawing methods provided by CANVAS H5; SVG has a history of more than 10 years. 2. Canvas drawing is based on pixels and is a bitmap. SVG is based on graphics and uses HTML tags to describe shapes, so zooming in and out will not be distorted. 3. Canvas needs to be drawn in JS; 4. Canvas supports more colors than SVG. 5. SVG can take tags and operate on themCopy the code
How does Flex work?
1. The container has the concepts of main axis and vertical axis. By default, main-axis is horizontal, from left to right, and vertical, from top to bottom. 2. The layout of all the children is influenced by these two axes. 3. There are a number of related CSS properties that change the orientation of the main and vertical axes to achieve different layout effects.Copy the code
What’s the difference between SRC and href?
1. Href refers to the location of the web resource and establishes a link between the current element (anchor) or document (link) for hyperlinking. 2. SRC is the position pointing to the external resource, which will be embedded in the document at the current tag position. SRC resources are downloaded and applied to documents when requested, such as JAVASCRIPT scripts, IMG images, and frame elements. When the browser parses the element, it suspends the downloading and processing of other resources until the resource is loaded, compiled, and executed, as do elements such as images and frames, similar to embedding the pointed resource in the current tag. This is why js scripts are placed at the bottom and not at the top.Copy the code
JavaScript Summary (extra effort)
1. How to understand this keyword in JS?
This refers to the current object. The reference to this depends on the context in which the call is made. By default, this refers to the Window object. Global: The global environment is inside, where this always refers to the Window object. Local environment: 1. Call the function directly under the global scope. This refers to the window. 2. Object function call, which object call refers to which object. 3. Instantiate the object with new. In the constructor, this points to the instantiated object. 4. Use call or apply to redirect this.
2. What is scope in JavaScript?
In JavaScript, each function has its own scope. A scope is basically a collection of variables and rules for how to access them by name. Only code in a function can access variables in the function scope.
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.
What is a closure
When I first explained closures, I used to say functions of functions; However, it does not correctly describe the exact meaning of closures.
Closures create a closed lexical scope in another scope. It usually returns automatically to generate the lexical environment. This environment consists of any local variables that were in scope when the closure was created. It is like a miniature factory, using these raw materials to produce products with specific functions.
4. Explain equality in JavaScript.
There are strict comparisons and cast comparisons in JavaScript:
A strict comparison (e.g. ===) checks whether two values are equal without allowing a forced transformation; Abstract comparisons (such as ==) check whether two values are equal if forced transitions are allowed.
var a = "42";
var b = 42;
a == b; // true
a === b; // false
Copy the code
If any of the values being compared may be true or false, use ===, not ==; If any of the values being compared are these particular values (0, “”, or []), use === instead of ==; In other cases, it is safe to use ==. Not only is it secure, but in many cases it simplifies code and improves code readability.
5. Explain the elevation of variables
Promotion of variables 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 they are declared. Initialization is not promoted; promotion only applies to declarations of variables.
var x = 1
console.log(x + The '-'Var y = 0; var y = 0Copy the code
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-side event responses. In theory, we could attach listeners to any DOM element in the HTML, but this is wasteful and unnecessary due to event delegation.
- What is event delegation? This is a technique that allows event listeners on parent elements to affect child elements as well. In general, event propagation (capture and bubbling) allows us to implement event delegation. 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 hits the original listener of the DOM binding (current target). The capture attribute converts the event phase to the capture phase, moving the event down to the element; Thus, the trigger direction is opposite to that of the bubble phase. The default value for capture is false.
7. Explain strict Mode
Strict patterns are used to standardize normal JavaScript semantics. Strict patterns can be embedded in non-strict patterns with the keyword ‘use strict’. The code using the strict mode should follow the strict syntax rules of JS. For example, semicolons are used after each statement declaration.
8. Explain null and undefined in JavaScript.
- There are two underlying types in JavaScript: NULL and undefined. They mean different things:
- Uninitialized: undefined;
- Null value: null.
//null and undefined are two different objectstrue
null === null //true
null == undefined //true
null === undefined //flase
Copy the code
9. Explain values and types in JavaScript.
JavaScript provides two types of data: basic data type and reference data type.
- String
- Number
- Boolean
- Null
- Undefined
- Symbol
Reference data types are:
- Object
- Array
- Function
10. Explain the event bubbling and how to stop it?
Event bubbling is when the most heavily nested element fires an event, which then fires on the parent element in the nested order.
One way to prevent event bubbling is to use event.cancelBubble (lower than IE 9) or Event.StopPropagation ().
11. What does window.onload do?
Window. onload is an event that is called after the document and resource have been loaded to ensure that the element has been loaded by the time the JS retrieves it.
12. What is your understanding of scope chains?
Scope chain is a kind of lookup mechanism in JS, from the current scope, the current scope does not look up the next level of scope, all the way to the outermost layer, if not found, is not define
13. Classification of timers? What are their differences and usage?
There are two types of timer in Js:setInterval: indicates intermittent execution.setTimeout: delay executionsetInterval(function, time) Time unit: mssetInterval(function() {}, 1000); Executing a function once every second is generally used for counting down, rotating graphssetTimeout(function, time) time unit: mssetTimeout(function() {}, 1000); Delay the execution of a function once a second, will only be executed once generally used for advertising, advertising pop-up layerCopy the code
14. Unduplicate the following strings and remove special characters. Sort the strings in alphabetical order before digits
As follows: "1233fDDf&3434FDSAFf&45454545444RFDSfds&545gDSgs" var STR = "1233fDDf&3434FDsaff&4545454RFDSfds &545gdsgs"; Var n = ""; var s="";
for(var i=0; i<str.length; i++){if((str[i]>=0&&str[i]<=9)&&n.indexOf(str[i])==-1){
n+=str[i];
}else if((str.charCodeAt(i)>=97&&str.charCodeAt(i)<=122)&&s.indexOf(str[i]) == -1){
s+=str[i];
}
}
console.log(n+s); //12345fdsarg
Copy the code
15. Intercept def in the string abcdefg.
Var STR = "abcdefg";if(STR. IndexOf (" def ")! = 1) {the console. The log (STR., substr (STR. IndexOf (" def "), 3)); }Copy the code
Pop () push() unshift() shift()?
Push: Adds one or more elements to the end of the array Pop: Removes an element from the end of the array and returns the deleted element Unshift: Adds or removes an element from the head of the array Shift: Removes an element from the head of the array and returns the deleted element
17. Split () join()?
The split is the method of the string, the string according to the specific symbol divided into an array Example: “u&s”. The split (” & “) — — — — — – [” u “, “s”] Join: is a method that array will be combined into a string array according to the sign [” u “, “s”]. Join (” – “) – ‘u -‘ s
18. Write an array deduplicate method.
function sort(arr) {
for(var i = 0; i<arr.length; i++){for(var j = i+1; j<arr.length; j++){if(arr[i] == arr[j]){ arr.splice(j,1); J -; }}}}}}}}}}}}}}return arr
}
Copy the code
19. Bubble sorting?
for(var i = 0; i<arr.length; i++){for(var j = 0; j<arr.length-i; j++){if(arr[j] > arr[j+1]){ // var temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; }}}Copy the code
20. How does DOM add, remove, move, copy, create, and find nodes
ParentNode Child node offsetParent Create document.createElement(' label name ') AppendChild (child) Parent. InsertBefore (newChild, refChild) Copies the copied node. CloneNode (trueRemove () parent removeChild (child) replace parent replaceChild (newChild, refChild)Copy the code
21. What is a Window object? What is a Document object?
Window is the largest object in JS, stands for window, contains document Document document document object, stands for HTML
22. What is the difference between offsetWidth, clientWidth and scrollTop?
OffsetWidth: placeholder width, including content width + left/right padding+ left/right padding scrollTop: height of the page to be rolled out
23. How do I obtain the search content from the URL?
window.location.search
24. What is the difference between events, IE and Firefox’s event mechanism?
IE’s event stream is bubbling, while Firefox supports both bubbling and capturing.
25. What is the difference between event binding and normal events?
Event: If you add the same event to the same element, the next one overwrites the previous event binding: you can add the same event to the same element without overwriting it
26. Explain the flow of events?
Event capture phase: When an event occurs, the event is passed from window to child elements in turn to determine the target phase: Determine the event target Event bubble phase: The event target starts to process the event, after processing, the event will be passed to the parent element in turn, until the Window event is bubbled in the event processing, IE only bubble
27. How many events are there in drag effects?
Click onMouseDown, drag onMousemove, pop up OnMouseup
28. What are the advantages and disadvantages of cookies?
Advantages: High scalability and availability 1. Control the size of session objects stored in cookies through good programming. 2. Use encryption and secure transmission technology (SSL) to reduce the possibility of cookies being decrypted by Po. 3. Store insensitive data only in cookies, so there will be no significant loss even if it is stolen. 4. Control the lifetime of cookies so that they do not last forever. The thief probably got hold of an expired cookie. Disadvantages: 1. Limit the number and length of cookies. Each domain can have a maximum of 20 cookies. The length of each cookie cannot exceed 4KB; otherwise, the cookie will be truncated. 2. Security issues. If the cookie is intercepted, that person can get all session information. Even encryption is useless, because the interceptor does not need to know the meaning of the cookie, as long as he forwards the cookie can achieve the goal. 3. Some states cannot be saved on the client. For example, to prevent forms from being submitted repeatedly, we need to save a counter on the server side. If we keep this counter on the client side, it does nothing. Because of these drawbacks (mainly cookie size and how much are limited, and every time you request a new page when cookie will be sent in the past, so virtually wasted bandwidth, in addition to the cookie also need to specify the scope, can not be cross-domain call), IE8 later, there will be a Web storage; It exists only for local caching of data; But cookies are also indispensable: they interact with the server and exist as part of the HTTP specification.Copy the code
29. What is the difference between call() and apply()?
Call (this, parameter 1, parameter 2…); Apply (this,[parameter 1, parameter 2…]) )
The process of creating Ajax.
function ajax(json) {
json.data = json.data||""; / / if there is no request parameters, empty json. The contentType = json. The contentType | | "application/x - WWW - form - urlencoded"; // If there is no character encoding, use the default //1. Create objectif(window.xmlhttprequest){// Normal var ajax = new XMLHttpRequest(); }elseVar ajax = new ActiveXObject(" microsoft.xmlhttp "); } //2. Establish a connectionif(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. Listen for ajax.onreadyStatechange =function () {
if(ajax.readyState == 4){
if(ajax.status == 200){ json.success(ajax.response); }}}}Copy the code
31. The difference between GET and POST for Ajax requests and when to use POST.
A GET request passes parameters after the URL, while a POST request is sent to the WEB server as the physical content of an HTTP message. Of course, in Ajax requests, this difference is not visible to users. 2. GEt transmits data with a small capacity and is insecure, while POST transmits data with a large content and is more secure. It is safer to select POST when sending some data to the server
32. How to interpret JSON data when making Ajax requests.
Parse (data) if json is a string: eval(“(“+ajax.response+”)”)
33. What is the difference between synchronous and asynchronous?
Asynchronous: When the client requests data from the server, it can do other things. Synchronous: When the client requests data from the server, it cannot do other things
34. Common HTTP status codes?
200 404 503 200 status code: indicates that the request was successful. 201 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. If the required resource cannot be established in time, return ‘202 Accepted’ 202 status code: the server Accepted the request, but has not yet processed 301 status code: the requested resource has been permanently moved to a new location. When the server returns this response (a response to a GET or HEAD request), it automatically forwards the requester to the new location. 302 Status code: The requested resource temporarily responds to the request from a different URI, but the requester should continue to use the same location for future requests. 304 The requested page has not been modified since the last request. When the server returns this response, the web page content is not returned. If the web page has not changed Since the requester last requested it, you should configure the server to return this response (called the if-Modified-since HTTP header). 301 Status code: The requested resource is permanently moved to a new location. When the server returns this response (a response to a GET or HEAD request), it automatically forwards the requester to the new location. 302 Status code: The requested resource temporarily responds to the request from a different URI, but the requester should continue to use the same location for future requests. 304 The requested page has not been modified since the last request. When the server returns this response, the web page content is not returned. If the web page has not changed Since the requester last requested it, you should configure the server to return this response (called the if-Modified-since HTTP header). 401 Status code: The request requires authentication. The server may return this response for a web page that requires login. 403 Status code: The server understands the request, but refuses to execute it. Unlike the 401 response, authentication does not help, and the request should not be submitted twice. 404 Status code: The request fails because the requested resource is not found on the server. There is no information to tell the user whether the condition is temporary or permanent. If the server is aware of the situation, it should use the 410 status code to tell the old resource that it is permanently unavailable due to some internal configuration mechanism and that there are no reachable addresses. The 404 status code is widely used when the server does not want to reveal exactly why the request was rejected or when no other suitable response is available. 500 status code: The server encountered an unexpected condition that prevented it from completing processing the request. Typically, this problem occurs when the server’s code fails. 503 Status code: The server is currently unable to process requests due to temporary server maintenance or overload. Usually, this is a temporary state that will recover over time
35. Which js operations will cause memory leaks?
Function leak(){leak= “XXX”; //leak becomes a global variable and will not be recycled} 2) forgotten timer or callback 3) memory leak caused by closure
36. What is the difference between $(document).ready() and window.onload?
Onload overwrites the difference between “Ready” and “window.onload”. “Window.onload” overwrites the difference between “ready” and “window.onload”. “Window.onload” is called when documents and resources are loaded
37. How to solve cross-domain problems?
KaTeX Parse Error: Expected ‘EOF’, got ‘&’ at position 34:… Script SRC = “url & ̲ callback = showDa… In the.Ajax () method, you simply configure a dataType: ‘jSONp’ to make a cross-domain request
ES6
1. Var let const difference
-
Variables declared by.var and const do not mount on window:
var a = 100; console.log(a,window.a); / / 100 100let b = 10;
console.log(b,window.b); // 10 undefined
const c = 1;
console.log(c,window.c); // 1 undefined
Copy the code
(2). Var implements variable promotion, while let and const do not
console.log(a); // undefined ===> undefined = 100;Copy the code
console.log(b); B is not defined ===let b = 10;
Copy the code
console.log(c); Const c = 10; c is not defined ===> const c = 10;Copy the code
(3).let and const declarations form block scopes
if(1){
var a = 100;
letb = 10; } console.log(a); // 100 console.log(b) // Error: b is not defined ===> The variable B cannot be foundCopy the code
if(1){ var a = 100; const c = 1; } console.log(a); // 100 console.log(c) // Error: c is not defined ===> Cannot find the variable CCopy the code
(4). Let and const cannot declare variables of the same name in the same scope. Var does
var a = 100; console.log(a); // 100 var a = 10; console.log(a); / / 10Copy the code
let a = 100;
leta = 10; // Console error: Identifier'a'Has already been declared ===> Identifier A is already declared.Copy the code
-
(5) Temporary dead zone
var a = 100;
if(1){ a = 10; // a is used in the current block scopelet// If we assign a value of 10 to a, we will only look for the variable a in the current scope, so console Error:a is not definedlet a = 1;
}
Copy the code
-
(6).const
1. Do not use null placeholders once you declare that an assignment must be made. * *     2, after the declaration can not be modified;   Const a = 100; * * */ const a = 100; const list = []; list[0] = 10; console.log(list);     // [10] const obj = {a:100}; obj.name ='apple'; obj.a = 10000; console.log(obj);     // {a:10000,name:'apple'}
Copy the code
2. Arrow function
(1) Do not use the function keyword to create functions
- Es5 creates functions
var aa = function() {}
Copy the code
- Es6 creates functions
var aa = () => {}
Copy the code
(2) Can be extremely short function
- Es5 function
var fn = function(a) {
return a + 5
}
Copy the code
- The arrow function can be abbreviated as:
var fn = a => a + 5;
Copy the code
- Shorthand rule:
If the function passes only one argument, you can remove (). Eg: (a) => {} short: a => {} when the body of the function returns only the value, you can remove {}; eg: (a, b) => {returnA +b} => a+ BCopy the code
(3) When dynamic context is required, you cannot use the arrow function, which is the immobilization of this.
When we define a function with =>, this refers to the object at which we defined it, not to the object at which we used it. 2. Cannot be used as a constructor, that is, cannot use the new command, otherwise an error will be thrown; Can't use arguments objects; 4, do not use yield command;Copy the code
3. Add four common methods to the array
(1) Map
letArr =,59,80 [66];let result=arr.map(item => {
if(item >= 60){
return "Pass"
}else{
return "Fail"}}); //result:["Pass"."Fail"."Pass"]
Copy the code
(2) reduce — summarize
letArr =,69,180,8763 [12];let result = arr.reduce((tmp, item, index) => {
console.log(tmp, item, index);
returntmp + item; }); console.log(result); / / sumCopy the code
(3) filter
let arr=[
{title: 'Power cord', price: 50},
{title: 'computer', price: 13000},
{title: 'keyboard', price: 120},
{title: 'mobile phone', price: 9000}
];
letresult=arr.filter(json=>json.price>=5000); console.log(result); //[{title:'computer', price: 13000},{title: 'mobile phone', price: 9000}]
Copy the code
(4) forEach — iteration
letArr =,5,8,9 [12]; arr.forEach((item,index)=>{ console.log(index+':'+item); //0: 12 1: 5 2: 8 3: 9});Copy the code
4. Parameters of the function
(1) Collect parameters
functionshow(a, b, ... The args) {the console. The log (args)} show (6) / / output,4,5,6 [3]Copy the code
(2) Expand array
Const arr1 = [1, 2, 3]; Const arr2 = (4 and 6); console.log([...arr1, ...arr2]); // output [1,2,3,4,5,6] console.log(... arr1); // output 1,2,3Copy the code
(3) Default value
const show = (a=666, b=999) => { console.log(a); // output 666 console.log(b); } show();Copy the code
5. Deconstruct assignments
(1) The left and right sides of the structure must be the same;
(2) The right-hand side must be a legal value;
(3) Declaration and assignment cannot be separated (must be done in one sentence);
let[a, b, c] =,2,3,999 [1];let{e,d,g}={e: 4, d: 5, f: 6, g: 7}; console.log(a,b,c,e,d,g); // Output 1, 2, 3, 4, 5, 7Copy the code
6. The string
(1) Two new methods: startsWith endsWith
//startsWith
let str='https//http://mp.blog.csdn.net/postedit/79478118';
if(str.startsWith('http://')){
alert('Common Url');
}else if(str.startsWith('https://')){
alert('Encrypted URL');
}else if(str.startsWith('git://')){
alert('git address');
}else if(str.startsWith('svn://')){
alert('the SVN address');
}else{
alert('other');
}
Copy the code
//endsWith
let str='12121.png';
if(str.endsWith('.txt')){
alert('Text file');
}else if(str.endsWith('.jpg')){
alert('JPG images');
}else{
alert('other');
}
Copy the code
(2) String template
Advantages: convenient string concatenation; Can fold line
let title='title';
let content='content';
let str='
\
'
+title+'\ '
+content+'</p>\
</div>';
let str2=`<div>
<h1>${title}</h1>
<p>${content}</p>
</div>`;
Copy the code
7. Promise implementation principle? Three states of promise
Promise actually addresses jquery’s Ajax callback territory (addressing layers of nesting) and is just a solution for asynchronous programming
new promise(function(resolve,reject) {
// 111111111
resolve('... ')
} ).then(function(value) {
console.log(value)
}).catch(function(error){
console.log(error)
})
Copy the code
const p1 = new Promise(function (resolve, reject) {
setTimeout(() => reject(new Error('fail')), 3000)
})
const p2 = new Promise(function (resolve, reject) {
setTimeout(() => resolve(p1), 1000)
})
p2
.then(result => console.log(result))
.catch(error => console.log(error))
Copy the code
This is a big pity. The state of the object is not affected by the outside world, and once the state changes, it will never change again. This result can be achieved at any time.
Disadvantages: Promise cannot be canceled; if no callback function is set, errors will be thrown inside the promise. Third, while in the pending state, there is no way to tell what stage of progress is currently in progress (just started or nearly completed).
8. Understanding of ES6
ECMAScript 6.0 (ES6) is the next generation standard for the JavaScript language, which was officially released in June 2015. Its goal is to make JavaScript an enterprise-level development language that can be used to write complex, large-scale applications.
vue
1. What is MVVM?
MVVM stands for model-view-ViewModel. MVVM is a design idea. The Model layer represents the data Model, where you can also define the business logic for data modification and manipulation; A View represents the UI component that is responsible for converting the data Model into a UI presentation. A ViewModel is an object that synchronizes the View and Model.
In MVVM architecture, there is no direct connection between View and Model, but interaction through ViewModel. The interaction between Model and ViewModel is bidirectional, so the changes of View data are synchronized to Model. Changes to Model data are immediately reflected in the View.
The ViewModel connects the View layer with the Model layer through two-way data binding, and the synchronization between View and Model is completely automatic without human intervention, so developers only need to focus on business logic, do not need to manually manipulate DOM, do not need to pay attention to the synchronization of data state. Complex data state maintenance is managed entirely by MVVM.
2. The difference between MVVM and MVC?
MVC and MVVM are not that different. It’s all a design idea. Basically, the Controller in MVC morphed into the viewModel in MVVM. MVVM mainly solves the problem that a large number of DOM operations in MVC reduce page rendering performance, slow loading speed and affect user experience. And when the Model changes frequently, developers need to actively update the View.
3. What are the advantages of Vue?
- Low coupling. Views can be changed and modified independently of Model. A ViewModel can be bound to different “views”. The Model can remain unchanged when the View changes, and the View can remain unchanged when the Model changes.
- Reusability. You can put some view logic in a ViewModel and have many views reuse that view logic.
- Independent development. Developers can focus on business logic and data development (viewModels), designers can focus on page design, and Expression Blend makes it easy to design interfaces and generate XML code.
- Can be tested. Interfaces are harder to test, and tests can now be written against the ViewModel.
4. What is the VUE lifecycle? Understanding the VUE lifecycle?
- What is the role of the VUE lifecycle? A: It has multiple event hooks throughout its lifecycle, making it easier to form good logic when controlling the process of the entire Vue instance.
- Which hooks are triggered the first time the page loads? Answer: beforeCreate, Created, beforeMount, and Mounted are triggered the first time the page is loaded
- The life cycle
A: There are 8 stages: before/after creation, before/after loading, before/after updating, and before/after destruction.- Before/After: In the beforeCreate phase, the mount element EL of the Vue instance does not exist yet.
- Before/After loading: In the beforeMount phase, the vue instance’s $EL and data are initialized, but the previously virtual DOM node is still mounted, and data.message has not been replaced. In mounted phase, vue instance is mounted and data.message is successfully rendered.
- Before/After update: When data changes, the beforeUpdate and updated methods are triggered.
- Before/after destroy: Changes to data do not trigger periodic functions after destroy, indicating that the vue instance has been unbound from event listening and the DOM structure still exists
- Describe briefly what scenarios are appropriate for each cycle? Mounted can be used for either of the following applications: beforecreate or beforecreate the loading event for a loaded instance. Mounted can be used for either of the loading events or for both of the loading events. Updated: If data is handled uniformly, write the corresponding function here. BeforeDestroy: You can make an acknowledgement box for the stop event nextTick: Dom Arguments is a pseudo-array that has no traversal interface and cannot be traversed
5. Name at least 4 vUE commands and their usage.
V-if: determines whether to hide. V-for: data loop out; V-bind :class: to bind a property; V-model: implements bidirectional binding
6. What is vue-loader? What are the uses for it?
A loader that parses.vue files and converts them into JS modules with template/js/style. Use: JS can write ES6, style style can SCSS or less, template can add Jade, etc
7. Value transfer between components?
- Parent and child components pass values
<template> <Main :obj="data"></Main> </template> <script> // introduces the child component import Main form"./main"
exprot default{
name:"parent".data() {return {
data:"I'm going to pass data to a child component."}}, // Initialize the component components:{Main}}</ script> // The child component accepts data via the props method <template> <div>{{data}}</div> </template> <script> exprot default{ name:"son"// Props :["data"]
}
</script>
Copy the code
- The child component passes data to the parent
// The child component passes$emitThe <div id= method passes the argument"app"> <! -- reference parent component --> < son@func ="getMsg"></son> <! -- Component template definition --> <scripttype="x-template" id="son">
<div>
<input type="button" value="Pass value to parent" @click="sendMsg"/> </div> </script> </div> <script>'son', {
template: '#son'// Component template Id methods: {sendMsg() {// Button click event this.$emit('func'.'OK'); // Call the method passed by the parent while passing the data}}}); Var vm = new Vue({el:'#app', data: {}, methods: {getMsg(val){// In the child component, pass this.$emitAlert (val); alert(val); }}}); </script>Copy the code
8. What is the definition of nested set?
In real projects we will encounter a combination of multi-layer nested components, but how do we implement nested components? Therefore, we need to use the children configuration in the parameters of the VueRouter, so that we can achieve good route nesting. Index.html, with only one exit
<div id="app"> <! <router-view></router-view> </div>Copy the code
Main.js is a redirect that displays the home component as soon as the page loads. The redirect must be consistent with the path component. Children is the child route, and of course the child route can also be nested in the child route.
import Vue from 'vue'
import VueRouter from 'vue-router'Vue.use(VueRouter) // Import two components import home from"./home.vue"
import game from "./game.vue"// const routes = [{path:"/", redirect: "/home"},// redirect to the home component {path:"/home", component: home,
children: [
{ path: "/home/game"Const router = new VueRouter({routes}) new Vue({el:'#app', data: {}, methods: {}, router}) //home.vue, click "Display" to display the child route. The egress of the child route must be inside the parent route, otherwise the child route cannot be displayed.Copy the code
9. Hop between routes?
- Declarative (label jump)
- Router. Push (‘index’)
- Webpack provides require.ensure() to implement on-demand loading. In the past, routes were imported through import. Instead, they are imported using const routes.
- No page loading on demand introduction:
import home from '.. /.. /common/home.vue'
Copy the code
- Introduction of page loading on demand:
const home = r => require.ensure( [], () => r (require('.. /.. /common/home.vue')))
Copy the code
10. What is vuex? How to use it? Which functional scenarios use it?
State management in vUE framework. Import store and inject in main.js. Create a new directory store… . Export. The scenarios are as follows: Status between components in a single-page application. Music play, login status, add shopping cart
// Create store.js import vue from'vue'
import vuex form 'vuex'
vue.use(vuex)
exportdefault new vuex.store({ //... code }) //main.js import store from'./store'.Copy the code
11. What kinds of navigation hooks does vue-Router have?
Three kinds of
- Global navigation hook
router.beforeEach(to, from, next),
router.beforeResolve(to, from, next),
router.afterEach(to, from )
Copy the code
- Component internal hook
beforeRouteEnter,
beforeRouteUpdate,
beforeRouteLeave
Copy the code
- Separate routing proprietary components
beforeEnter
Copy the code
12. What are the methods of custom instruction (V-check, V-focus)? What hook functions does it have? What other hook function parameters are there
Global directives: The directive method of a Vue object takes two arguments, the directive name and the function. Directives defined in the component: directives hook function:bind[Binding], [node is inserted], [Update] Hook function parameters: EL, bindingCopy the code
What is the principle of bidirectional binding of VUE?
Vue. js adopts data hijacking combined with publiser-subscriber mode. It hijacks the setter and getter of each attribute through Object.defineProperty() to publish messages to subscribers when data changes and trigger corresponding listening callback.
The first step is to perform recursive traversal of the observe data object, including the property of the child property object with setter and getter. If you assign a value to the object, the setter will be triggered and the data changes will be monitored
Step 2: Compile parses the template instruction, replaces the variables in the template with data, and initializes the render page view, binds the corresponding node of each instruction to update function, adds the subscriber that listens to the data, receives notification once the data changes, and updates the view
Step 3: The Watcher subscriber acts as a communication bridge between the Observer and Compile. It mainly does the following:
- Add yourself to the attribute subscriber (DEP) during self instantiation
- There must be an update() method itself
- If you can call your own update() method and trigger the callback bound with Compile when notified of property changes to dep.notice(), you are done.
- Step 4: MVVM, as the entry of data binding, integrates Observer, Compile and Watcher, uses Observer to monitor its model data changes, and uses Compile to parse and Compile template instructions. Finally, Watcher is used to build a communication bridge between Observer and Compile to achieve data change -> view update; View Interactive Changes (INPUT) -> Bidirectional binding effect of data model changes.
14. What are the attributes of vuex
There are 5 types, including state, getter, mutation, Action and Module
15. What are the store features of Vuex
- Vuex is a repository of objects. Where state is where the data source is stored, corresponding to data in a normal VUE object
- The data stored in state is reactive, and the VUE component reads data from the Store. If the data in the Store changes, the components that depend on that data will also be updated
- It maps the global state and getters to the computed properties of the current component through mapState
16. What is the getter feature of Vuex
- A getter can evaluate state, which is the store’s evaluated property
- Getters can be reused across multiple feeds, although computed properties can also be done within components
- If a state is only used within a component, you can do without getters
17. What are the mutation characteristics of VUEX
- Action is similar to Muation except that the action commits mutation rather than a direct state change
- Actions can contain any asynchronous operation
- If it is reused elsewhere, place the request in an action for easy reuse and return it wrapped as a promise
18. What are the problems caused by not using VUex
- Maintainability goes down, you have to change the data, you have to maintain 3 places
- Poor readability because you can’t tell where the data in a component is coming from
- The added coupling, the large number of uploads and distributions, will greatly increase the coupling. Originally, Vue used Component to reduce the coupling, but now it is used in this way, which is not the original intention of componentization
19. Vuex principle
Vuex exists only as a plug-in for VUE. Unlike Redux,MobX and other libraries that can be applied to all frameworks, Vuex can only be used on VUE, largely because it is highly dependent on VUE’s computed dependency detection system and its plug-in system.
The overall idea of VUEX was born in Flux, but its implementation completely uses the responsive design of VUE itself. The dependent listening and collection belong to the proxy hijacking of the object Property set GET method by VUE. The store in Vuex is essentially a hidden vue component without a template.
20. How does Vuex distinguish whether state is modified directly externally or by mutation method?
The only way to change state in Vuex is to call commit(‘xx’, payload), which sets the _research flag variable to true by calling this._withcommit (fn), and then change state, You also need to restore the _research variable. External changes can change state directly, but they don’t change the _research flag (right), so just watch state and determine whether the _research value is true (right) when state change.
21. What is Axios? How to use it? Describes the process of using it to implement the login function
Axios is the module that requests background resources. npm i axios -S
If a cross-domain request is sent, you need to configure it in the config/index.js configuration file
22. Should the Ajax request code in vUE be written in component methods or vuex actions
If the requested data is not intended to be shared by other components and is only used within the requested component, it does not need to be placed in the VUEX state
23. How do I make CSS work only in the current component?
Change the style of the current component to Style scoped
24. What are the similarities and differences between V-show and V-IF directives?
- The V-show directive changes the displayCSS property of an element to show or hide it
- The V-if directive destroys and reconstructs the DOM to show and hide elements
Write in the last
Collection is not easy if you think it is useful to move a thumbs-up to support it, collection is always useful, thank you ~