preface
Earlier interviews (including alibaba’s telephone interview), have met some questions, and in higher probability of questions/written test, interview some of the answer is not very good to hang out, today finally have time to organize Shared with everyone, main content is divided into two parts: encountered during the interview, see think worth imprint in the process of review; If you have any misunderstanding or inadequacy, please comment and correct IT. I am South Su ^_^ ~, chief pit filling officer of @it · teamhead alliance
HTML
民运分子
What is a box model?
民运分子
Some interviewers will ask you about your understanding of the box model. In a typical web page, each tag element inside is composed of several parts: Content, margin, padding, and border. When you say these words, the interviewer is not going to be happy with this answer. Because there is a key point (IE box model and standard box model difference) — IE box model content includes border, padding
民运分子
2. How many methods are there to import styles to a page?
民运分子
-
The link tag is introduced, which is also one of the most commonly used methods. It belongs to XHTML tags. In addition to loading CSS, it can also define rel, Type, media and other attributes.
-
@import is introduced. @import is provided by CSS and can only be used to load CSS.
-
Style embed mode is introduced into, reduce page request (advantages), but will only be effective for the current page, and can’t reuse, will lead to redundant code, does not favor the maintenance project (disadvantages), and this way will project the main home page only commonly used (tencent, taobao, netease and sohu) and other large web site home page, before you have seen is this way, but some also abandoned;
Summary: When a link page is loaded, link will be loaded at the same time, while the CSS referenced by @import will wait until the page is loaded. Link is an XHTML tag, and there is no compatibility problem. Link supports dynamic JS to control DOM nodes to change styles, while @import does not.
民运分子
What are block elements, inline elements, and empty elements and what are the differences between them?
民运分子
-
The inline elements are: a, b, SPAN, img, input, SELECT, textarea, em, img, strong.
-
Block-level elements include ul, OL, LI, DL, DT, DD, H1, H2, H3, H4… P, section, div, form, etc.
-
,
,,,,,
Summary: Block elements are always on a single line, and margins don’t work on inline elements;
民运分子
What is your understanding of cookies, sessionStorage and localStorage?
民运分子
-
Cookies are data stored (usually encrypted) on a user’s local terminal by a website to identify the user. Cookie data is always carried in the same HTTP request and is passed back and forth between the browser and the server.
-
SessionStorage and localStorage do not automatically send data to the server and only store data locally.
-
Size: Cookie data size cannot exceed 4K. SessionStorage and localStorage, while also limited in size, are much larger than cookies, reaching 5M or more.
-
Timeliness: localStorage stores persistent data. Data will not be lost after the browser is closed unless the user takes the initiative to delete data or clear the browser/application cache. SessionStorage data is automatically deleted after the current browser window is closed. Cookie The cookie set remains valid until the expiration time, even if the window or browser is closed
-
Some interviewers may go a little further:
1) How to disable cookie browser after closing? — Do not set any positive, negative or 0 time for cookie;
2) Is the data of sessionStorage interoperable and shared between multiple Windows of browser (same-domain)? — No, both are independent, localStorage will share;
3), can let localStorage also set expiration time like cookie? The answer is yes, when storing data, also store a timestamp. Before getting the data, compare the current time with the timestamp you stored before. See another post I wrote earlier.
民运分子
5. Briefly explain your understanding of HTML semantics.
民运分子
-
Semantization refers to choosing the right tag (code semantization) according to the type of content, that is, doing the right thing with the right tag;
-
HTML semantics make the content of the page structured, structure more clear, help the browser, search engine analysis of the content of the capture;
-
Semantic HTML can present better content structure and code structure without CSS.
-
Search engine crawlers also rely on HTML tags to determine the context and the weight of each keyword, which is good for SEO.
CSS
民运分子
1, position is static, relative, absolute, fixed?
民运分子
absolute
: absolute positioning, the element is positioned relative to the first parent element whose value is not static (all the way up to the parent node), and it is out of normal document flow and does not occupy space; Fixed: The same is absolute, but the element is positioned relative to the browser window, rather than the position of the parent node (not supported below Internet Explorer 9).relative
: Relative positioning, the element is positioned relative to its normal position, belonging to normal document flow;static
The default value of position is top, bottom, left, right, z-index.inherit
: Specifies that the value of the position attribute be inherited from the parent element.
民运分子
1. How can you center an element vertically/horizontally (vertically)?
民运分子
-
Horizontal and vertical center — Method one
.div-demo{ width:100px; height:100px; background-color:#06c; margin: auto; position:absolute; top: 0; left: 0; bottom: 0; right: 0; }
-
Horizontal and vertical center — Method two
.div-demo{ width:100px; height:100px; background-color:#06c; margin: auto; position:absolute; top: 50%; left: 50%; transform: translate(-50%,-50%); -webkit-transform: translate(-50%,-50%); }
-
Horizontal and vertical center — Mode three, (compatible with old and new expansion boxes)
html,body{ height:100%; } .container{ display: box; display: -webkit-box; display: flex; display: -webkit-flex; -webkit-box-pack: center; -webkit-justify-content: center; justify-content: center; -webkit-box-align: center; -webkit-align-items: center; align-items: center; } .div-demo{ width:100px; height:100px; background-color:#06c; } </style>
3. Have you ever written a triangle icon with pure CSS style in the project?
<body class="container">
<div class="div-angles"></div>
<div class="div-angles right"></div>
<div class="div-angles bottom"></div>
<div class="div-angles left"></div>
<style>
html,body{
height:100%;
}
.container{
display: box;
display: -webkit-box;
display: flex;
display: -webkit-flex;
-webkit-box-pack: center;
-webkit-justify-content: center;
justify-content: center;
-webkit-box-align: center;
-webkit-align-items: center;
align-items: center;
}
.div-angles{
width: 0;
height: 0;
border-style: solid;
border-width:30px;
width:0px;
height:0px;
border-color: transparent transparent #06c transparent;
}
.right{
border-color: transparent transparent transparent #06c ;
}
.bottom{
border-color: #06c transparent transparent ;
}
.left{
border-color: transparent #06c transparent transparent;
}
</style>
</body>
Copy the code
民运分子
4. What is margin merging and has it been encountered in the project?
民运分子
- Yes, margin merge means that when two vertical elements both have a margin set, they will form a margin. The height of the merged margins is equal to the larger of the two merged margins.
民运分子
5, :before and :after two false elements, usually use double colon or single colon? What’s the difference? And what they do:
民运分子
- The single colon (:) is used for CSS3 pseudo-classes, and the double colon (::) is used for CSS3 pseudo-elements. (A pseudo-element consists of a double colon and a pseudo-element name);
- The double colon was introduced in the current specification to distinguish pseudo-classes from pseudo-elements. Browsers need to support older pseudo-elements, such as :first-line, :first-letter, :before, and :after. The new pseudo-elements introduced in CSS3 are not allowed to support the old single colon.
- To make the insertion appear before anything else, use ::before and ::after;
- In code order ::after also generates later content than ::before. If the stack view is pressed, ::after will generate content above ::before;
6. Chrome, Safari and other browsers, when the form submission user chooses to remember the password, the background of the automatic filling form becomes yellow next time, which affects the visual experience. Can I change it?
input:-webkit-autofill, textarea:-webkit-autofill, select:-webkit-autofill { background-color: #fff; // Set the color of the element to background-image: none; color: rgb(0, 0, 0); } // input:-webkit-autofill {-webkit-box-shadow: 0px 0 3px 100px # CCC inset; // Background color}Copy the code
7. The minimum font size of the browser is 12px. What should I do if I want to make it smaller?
-
Use pictures: if the content displayed is basically fixed, you can directly cut the picture compatibility is perfect (less than absolutely necessary, not recommended);
-
Find UI designer communication: in order to compatible with the major mainstream browser, avoid late designers to find you quarrel, take the initiative to find TA communication, explain the reason ———— pay attention to the tone, good talk don’t excited, more can’t carry a knife to force;
-
CSS3: CSS3 style transform: scale(0.7), scale has scale function;
-
“Display :table; Display: table – cell;” You can do that. You haven’t.
民运分子
8. How many ways do you have to implement the 0.5px border on the mobile end?
民运分子
-
DevicePixelRatio: The window object has a devicePixelRatio property, the ratio of device physical pixels to device-independent pixels, i.e. DevicePixelRatio = physical pixels/independent pixels; This way is very troublesome, JS detection, and then add class name control to the element, difficult to maintain;
-
Cut: direct.5px cut, this way is too low, it is recommended not to use, especially difficult to maintain, HD screen paste, more important is to be seen by peers will feel you are very scum ~;
-
Image background: CSS3 background-image: Linear-gradient, the disadvantage is: there are many styles, encounter rounded corners this scheme will cup drama;
-
Box-shadow: inset 0px 1px 1px-1px #06c; box-shadow: inset 0px 1px 1px-1px #06c; Not used, but many comments, baidu suggested their own;
-
Transform: scale(0.5); transform: scale(0.5); It can basically meet all scenarios, and it is also very convenient to handle rounded corners
-
The code of plan 3 and 5 is also used by the company at present:
//3, css3 background-image@mixin border(top:1,top:1, top:1,right:1, bottom:1,bottom:1, left:1, color:#ebebf0) { background-image:linear-gradient(180deg, color, color50color 50%, transparent 50%), linear-gradient(90deg, color50color, color50color 50%, transparent 50%), linear-gradient(0deg, color50color, color50color 50%, transparent 50%), linear-gradient(90deg, color50color, color50color 50%, transparent 50%); background-size: 100% color50top + px, right+px100right + px 100%, 100% right+px100bottom + px, $left + px 100%; background-repeat: no-repeat; background-position: top, right top, bottom, left top ; }
@mixin borderTop(top:1,top:1, top:1,color:#ebebf0) {@include border(top,0,0,0, 0,top, 0,0,0,color); } @ mixin borderRight (right: 1, right: 1, right: 1, color: # ebebf0) {@ include border (0, right, 0, 0, right, 0, 0, Right, 0, 0, color); } @mixin borderBottom( bottom:1,bottom:1, bottom:1,color:#ebebf0) { @include border(0, 0, bottom,0,bottom, 0, bottom,0,color); } @mixin borderLeft( left:1,left:1, left:1,color:#ebebf0) { @include border(0, 0, 0, left,left, left,color); } @mixin borderColor(color:#ebebf0) { @include border(1, 1, 1, 1, color); }
//5. Css3’s Transform: Scale, column by Chief Pit Filling Officer Su Nan, @ mixin MeiBin column borderRadius (width: 1, width: 1, width: 1, style: solid, color: # ebebf0, radius: 2 px) {position: relative; &:after{ left:0px; top:0px; right:-100%; bottom:-100%; border-radius: radius; Border – style: the radius; border-style: radius; Border – style: the style; border-color: color; Border – width: color; border-width: color; Border – width: the width + px; position:absolute; display:block; The transform: scale (0.5); – its – transform: scale (0.5); transform-origin:0 0; -webkit-transform-origin:0 0; content:”; }}
Javascript
1, please modify the following b function to ensure that each call to A +1:
function b(){ var a=1; }; function b(){ var a=1; return ()=>{ a++; return a; }}; let c = b(); c(); //2 c(); //3 c(); / / 4Copy the code
2. What are the basic data types of JS:
The ECMAScript standard defines seven data types:
-
Boolean
-
Null
-
Undefined
-
Number
-
String
-
Symbol :(as defined in ECMAScript 6, Symbol generates a globally unique value.)
-
Object :(Array, Function, Object)
3. Convert 386485473.88 to 386,485,473.88 with js:
Separator =(num)=>{if(! Num) {return '0.00'; }; let str = parseFloat(num).toFixed(2); return str && str .toString() .replace(/(\d)(? =(\d{3})+\.) /g, function($0, $1) { return $1 + ","; }); } separator(386485473.88) //"386,485,473.88" // Method 2: (386485473.88). ToLocaleString (' en-us ') // "386,485,473.88" supplemented by sRectCopy the code
4. What is the difference between js for and for in loops?
-
For loop array subscript typeof :number, for in loop array subscript typeof :string
Var southSu = [‘ southSu ‘,’18’,’ male ‘]; for(var i=0; i<southSu.length; i++){ console.log(typeof i); //number console.log(southSu[i]); / / jiangsu, shenzhen, 18, male} var arr = [‘ jiangsu ‘, ‘shenzhen’, ’18’, ‘male’, ‘handsome’]. for(var k in arr){ console.log(typeof k); //string console.log(arr[k]); // Su Nan, Shenzhen, 18, male, handsome}
-
A for loop cannot be used to loop objects and obj. Length cannot be obtained. When a for in loop iterates through the properties of an Object, all properties on the prototype chain are accessed. The solution: filter using the hasOwnProperty method or Object.keys returns an array of its own enumerable properties
Object.prototype.test = ‘property on prototype chain ‘; Var southSu = {name:’ southSu ‘,address:’ shenzhen ‘,age:18,sex:’ male ‘,height:176}; for(var i=0; i<southSu.length; i++){ console.log(typeof i); / / empty console. The log (southSu [I]); / / null}
for(var k in southSu){ console.log(typeof k); //string console.log(southSu[k]); // Su Nan, Shenzhen, 18, male, 176, Attributes on prototype chain}
5, bind events for each TD in the table with 1000+ TDS.
<body class="container"> <table id="table"> <tr><td>1</td><td>3</td><td>3</td><td>4</td><td>5</td></tr> <tr><td>1</td><td>3</td><td>3</td><td>4</td><td>5</td></tr> <tr><td>1</td><td>3</td><td>3</td><td>4</td><td>5</td></tr> ..................... </table> <script> let table =document.querySelector("#table"); table.addEventListener("click",(e)=>{ let {nodeName} = e.target; if(nodeName.toUpperCase() === "TD"){ console.log(e.target); //<td>N</td> } },false); </script> </body>Copy the code
5, js to a string of repeats (can count the number of character repeats is better), list your ideas (two or more) :
<script> let str = "12qwe345671dsfa233dsf9876ds243dsaljhkjfzxcxzvdsf"; let array = str.split(""); // array = [...new Set(array)]. Join (""); array = ((a)=>[...new Set(a)])(array).join(""); console.log(array); / / 12 qwe34567dsfa98ljhkzxcv filter only, not statistical / / scheme 2: function unique (arr) {const seen = new Map () return (arr) filter ((a) = >! seen.has(a) && seen.set(a, 1))).join(""); } console.log(unique(array)) // 12qwe34567dsfa98ljhkzxcv var news_arr = arr.sort(); For (var I =0; i<news_arr.length; i++){ if(news_arr[i] == news_arr[i+1] && news_arr[i]! = news_arr[i-1] ){ arrs.push(arr[i]); }; }; return arrs.join(""); } console.log(unique(array)) // 12qwe34567dsfa98ljhkzxcv for(var i=0; i<arr.length; i++){ let key = arr[i]; if(! obj[key] ){ obj[key]=1; }else{ obj[key]+=1; }}; return obj; } console.log(unique(array)) // object for each key and the number of times it is repeated </script>Copy the code
6. What performance optimization did you do before the project went online?
-
Images are preloaded, CSS style sheets are at the top and link is introduced, javascript is at the bottom before the body closing tag;
-
Use dns-prefetch to perform DNS pre-resolution for domain names used in projects, reducing DNS queries.
-
Reduce the number of HTTP requests: image static resources are hosted by CDN; CSS Sprites/SVG Sprites: How to insert SVG Sprites in the correct position? JS, CSS source compression, image size control appropriate, use iconFONT (font icon) or SVG, they are smaller and clearer than images, web Gzip compression;
-
Reduce DOM operation times and optimize javascript performance;
-
Reduce the number of DOM elements and make reasonable use of pseudo-classes such as :after and :before;
-
Avoid redirection and lazy loading of pictures;
-
Separate development of the front and back ends, load resources on demand, it is best to do the first screen straight out (i.e., server rendering);
-
Avoid CSS Expression, also known as Dynamic properties.
-
Multi-domain distribution division content to different domain names, to solve the browser domain name request concurrent number of problems, but also to solve the request to carry the default cookie problem;
-
Minimize the use of iframe, which blocks rendering of the main page;
-
Compress JavaScript, CSS, fonts, images, and even HTML for all resources;
-
With that in mind, welcome to add…
7. Your understanding of redrawing and rearrangement?
-
First, when a page is rendered several times, this can be called a rearrangement;
-
Changes to the DOM, style sheets, user events or behavior (mouse hovering, page scrolling, typing text into an input box, changing the size of a window, etc.) can cause a page to be rerendered, which requires regenerating the layout and redrawing nodes, called “rearranging” and “redrawing “;
-
Reduce or centralize operations on the page, that is, multiple operations are executed together;
-
In short, it can be summed up simply as: redrawing does not necessarily rearrange, but rearrangement must redraw.
-
You can see ruan’s analysis for more details
8. Have you ever made promises? Please write the following code execution results, and write your understanding of the idea:
setTimeout(()=>{ console.log(1); }, 0); new Promise((resolve)=>{ console.log(2); for(var i = 1; i < 200; i++){ i = 198 && resolve(); } console.log(3); }).then(()=>{ console.log(4); }); console.log(5); // Result: 2, 3, 5, 4, 1;Copy the code
-
First of all, js is a single thread execution, so the code execution sequence;
-
Have successively, that must have the rule (line up), otherwise disorderly, so how points successively? There are two kinds: synchronous and asynchronous;
-
Synchronization is very easy to understand, need not say more (I am the boss, you should give way to me);
-
Async (timer [setTimeout, setInterval], events, Ajax, Promise, etc.). When it comes to async, we need to subdivide macro task and micro task.
-
Macro task: when macro task is encountered in js asynchronous execution, it will execute the macro task first, add the macro task to the event queue, and then execute the micro task.
-
Micro tasks: In the process of asynchronous execution, microtasks will also be added to the event queue, but note that the identity of these two queues is not the same, not you come first, you go out first (just like the imperial concubine in the palace, not you come first (or queue first) to favor the first). When it is executed, the corresponding callback function is taken from the micro task first, and then the queue callback of the macro task is executed.
-
If you understand this order, then the results above are not hard to understand.
SetTimeout is asynchronous and will not be executed immediately. The new Promise immediately executes outputs 2 and 3, and between 2 and 3 executes resolve, the microtask; Console. log(5), output 5; And then the microtasks in asynchrony come out first, so you get 4; Finally execute macro task setTimeout output 1, if there is an error welcome to correct!
9. What did New SouthSu() do in this process?
Function SouthSu(){this.name = "SouthSu "; this.age = 18; This. address = "shenzhen "; }; let South = new SouthSu(); Console. log(South,South.__proto__ === southsu.prototype) //true Create an empty Object let p1 = new Object(); Set p1.__proto__ = SouthSu. Prototype; Let funCall = southsu.call (p1); let funCall = southsu.call (p1); Process the return value of the constructor: Determine the return type of SouthSu, if it is a value type then return obj, if it is a reference type then return the object of that reference type;Copy the code
10. What would you do at work if you were asked to implement a continuous animation using JS (e.g., rotary draw)?
-
Js to achieve animation, the first time that comes to mind is timer (setTimeout, setInterval);
-
Behind a window to js. RequestAnimationFrame, at the time said only remember there is such an API, the details have not been able to answer, want to listen to the interviewer what is the use of this API, ok is I was not well prepared and hope that other students will no longer make the same mistake;
Window. RequestAnimationFrame () method tells the browser you want to perform the animation and request the browser before the next redraw call the specified function to update the animation. This method takes as an argument a callback function that is called before the browser redraws, usually 60 times per second, which is the refresh rate that most browsers normally match the W3C recommendation. In most browsers, requestAnimationFrame() pauses calls while running in background tabs or hidden
<div class="angle-div"></div> <script> let timer = null; let Deg = 0; let distance = 360; var _requestAnimationFrame_ = window.requestAnimationFrame || window.webkitRequestAnimationFrame; let angleDiv = document.querySelector(".angle-div"); cancelAnimationFrame(timer); let fn = ()=>{ if(Deg < distance){ Deg++; }else{ Deg=0; }; angleDiv.style.transform = `rotateZ(${Deg}deg) translateZ(0)`; angleDiv.style.WebkitTransform = `rotateZ(${Deg}deg) translateZ(0)`; timer = _requestAnimationFrame_(fn); } timer = _requestAnimationFrame_(fn); </script>Copy the code
11. How to set HTTP cache?
1), Expires
Expires
The value of is the expiration time returned by the server, and the response tells the browser that it can read directly from the browser cache without requesting again. Disadvantages: The time on the server is returned, but the time on the client is compared. If the time is inconsistent, an error may occur.
2), the cache-control
Cache-Control
The fields that can be set are:private
: The client can cachepublic
: Both client and proxy servers can cachemax-age=xxx
: The cache content expires after XXX secondsno-cache
: Another cache strategy is needed to validate the cache (ETag
.Last-Modified
)no-store
: Does not cacheLast-Modified
: After the browser requests the file, the server returns the last modification time of the fileLast-Modified
The next request will be broughtIf-Modified-Since
Identification, ifIf-Modified-Since
If the value is equal to the file modification time of the server, the file is not modified and the 304 status code is returned. The browser reads the file from the browser cache. ifIf-Modified-Since
If the file modification time is shorter than that of the server, the browser resends the request to obtain the file and returns the status code 200.ETag
: A unique identifier of the server file, for example, the MD5 value of the file contentETag
Is returned to the browser. When the file changesETag
The value of theta will also change. I’ll bring it with me next timeIf-None-Match
Reserved by the browserETag
Value if a change is sent, the file is modified and needs to be re-requested, returning a 200 status code. Otherwise, the browser reads the file from the cache and returns a 304 status code.
Conclusion: — The relationship between several people
When cache-control is set to max-age=xx and a colleague sets Expires, cache-control takes precedence
When both ETag and Last-Modified exist, the server checks ETag first, then last-Modified, and decides whether to return 304 or 200
This article was supplemented by ZodiacSyndicate
民运分子
Shuffle an array randomly
-
Idea: Start at the end of the array, swap the first element at random, and work your way up
Const shuffle = arr => {let end = arr. Length-1 while(end) {// There is no swap when end is 0 const index = Math.floor(Math.random() * (end + 1)) [arr[index], arr[end]] = [arr[end], arr[index]] end -= 1 } return arr }
React implements a higher-order component that displays the mouse position
// Const mousePosition = Component => class extends React.Component {state = {x: 0, y: 0, } handleMouseMove = e => { this.setState({ x: e.clientX, y: e.clientY }) } render() { const { x, y } = this.state return ( <> <div onMouseMove={this.handleMouseMove}> <Component {... this.props} /> </div> <span>x: {x}</span> <span>y: {y}</span> </> ) } }Copy the code
Js part of the content is still sorting, will beContinuously updated
!
Special thanks: supplement from gold nuggets such as licongwen, sRect, and ZodiacSyndicate;
Recently just began to try to write blog, novice on the road, if there is something wrong in the article, please kindly correct. If you found this article helpful, please remember to like it. Want to know more about me? Welcome to follow the public account below.
Author: Su Nan – Chief Pit Filling Officer Communication group: 912594095, public account: honeyBadger8 Commercial reprint please contact @IT· Flathead brother alliance for authorization, non-commercial reprint please indicate the original link and source.
The link to the campaign 👉 autumn for job searching, writing there are gifts to send essay | the nuggets technology