preface

At the end of the year, the RESEARCH and development team was disbanded and unemployed, chose to go back to learn to drive, and successfully got the driver’s license. Recently, I returned to Shenzhen and began to set foot on the long road to find a job.

Pull hook hanging a hundred years do not match, BOSS Zhipin day and night did not respond.

Subject scope covers interview questions and I recently met pen (HTTP/Node/CSS/JS/Hybrid/Vue/NG/React)

Emm, I won’t list the companies here, if you read the whole thing, I believe you will have a lot of harvest, thank you for reading

  • Deadline for questions (March 23, 2018). I went to meet the entrepreneurs, both medium and large.
  • During death on all sides/two sides/three sides/all sides, also get part and push off partoffer, and some of the follow-up is unclear

Problem summary, think of as writing

Q: What styles can be inherited from CSS child elements?

  • Inheritable:font-size.font-weight.line-height.color.cursorEtc.
  • Non-inheritable items generally change the box model:display.margin,border,padding,heightEtc.

More comprehensive can be found in the engine

Q: What are the in-line elements? What are the block-level elements? What are the void elements?

  • Industry:input.span.a.imgAs well asdisplay:inlineThe elements of the
  • Block level:p.div.header.footer.aside.article.ulAs well asdisplay:blockthese
  • void: br.hr

Q: CSS3 implements a sector

  • The idea is the same as drawing solid triangles, but with a rounded Angle attribute

      
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>The fan</title>
  <style>
    .sector {
      width: 0;
      height: 0;
      border-width: 50px;
      border-style: solid;
      border-color: #f00 transparent transparent;
      border-radius: 50px;
    }
  </style>
</head>
<body>
  <div class="sector"></div>
</body>

</html>

Copy the code

Q: box-sizingWhat are the commonly used properties? What effect does each have?

Box-sizing has two values :content-box,border-box, and border-box.

This CSS is primarily a form of computation that changes the size of the box model

Some may ask about the padding-box, which was previously only implemented as a Firefox standard, but has been abolished in the current 50+ version.

Use a chestnut for the distance, a div has a width of 100px, a height of 5px, a border of 5px, and a padding of 5px

  <style>
    .test {
      box-sizing: content-box;
      border: 5px solid #f00;
      padding:5px;
      width: 100px;
      height: 100px;
    }

  </style>
  <div class="test"></div>
<! -- The content-box formula points the width and height to the content,border and padding Content + padding + border = 120px(the actual size of the box) Content (80px) + padding(5*2px) + border(5*2px) = 100px -->

Copy the code

Q: What are the ways to clear a float? Which one is better?

Commonly used for three kinds of commonly. Clearfix, clear: both, overflow: hidden;

The better one is. Clearfix, pseudo element all-in-one version, the latter two have limitations.. Try later pull

    .clearfix:after {
      visibility: hidden;
      display: block;
      font-size: 0;
      content: "";
      clear: both;
      height: 0;
    }


<!--For not hairzoom, _heightOf these,IE67 This kind of needcsshackIt's not on our radar anymore.clearfixThere's another way to write it,-->

.clearfix:before..clearfix:after {
	content:"";
	display:table;
}
.clearfix:after{
	clear:both;
	overflow:hidden;
}
.clearfix{
    zoom:1;
}

<!--display:tableTo avoid marginsmarginoverlappedmarginCollapse, the internal elements will become by defaulttable-cellThe form of the cell-->

Copy the code

Clear :both: If used in the same container adjacent elements, that is good, sometimes outside the container there are some problems, such as adjacent container layer elements collapse

Overflow :hidden: If this is used in the same container, it can form a BFC to avoid floating caused by the element collapse

Q: in the CSStransitionandanimateWhat’s the difference?animateHow to stay in the last frame!

This kind of question is different, and my answer is generally like this.. Let me stroke it.

Transition has no timeline, is triggered by an event, and has no intermediate state.

Animate, on the other hand, does animate effects, has the concept of a timeline (frame control), can be triggered repeatedly, and has intermediate states;

The overhead of transition is smaller than that of dynamic efficiency. The former is generally used for interaction, while the latter is mostly used for active pages.

How can you make animate stay at the last frame and just use one of its parameters

animation-fill-mode: forwards;
<! -- Backwards and backwards,both in turn -->
Copy the code

For example, let’s create a new HTML run ourselves.



      
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Box-sizing</title>
  <style>
    .test {
      box-sizing: border-box;
      border: 5px solid #f00;
      padding: 5px;
      width: 100px;
      height: 100px;
      position:absolute;
      /* @keyframes name: Animation name duration Duration timing function Animation frequency delay How long the animation is delayed to start the iteration-count loop number direction Animation mode, round trip or forward fill-mode Paused, playstate running start,paused, Check the documentation for more parameters.. I will not list */
      animation: moveChangeColor  ease-in 2.5 s 1  forwards running;
    }

    @keyframes moveChangeColor {
       from {
         top:0%;
         left:5%;
         background-color:#f00
       }
       to{
         top:0%;
         left:50%;
         background-color:#ced; }}</style>
</head>

<body>
  <div class="test"></div>
</body>

</html>


Copy the code

Q: Horizontal and vertical centralization of block-level elements

We’re going to consider two cases, fixed width height and variable width height;

There are multiple options, and I remember writing this kind of note early on

Portal: A guide to centering web elements

Q: Talk about the priority of style weight;

! Important > Inline Style > ID > class > tag

Style weights can be superimposed, such as ID >class

Q: Semantic understanding of HTML

In short: no overuse of tags (such as DIV)/ arbitrary nesting (such as span> DIV),

The naming of the class should be reasonable, conducive to browser parsing and engine inclusion, but also conducive to team collaboration and maintenance

Q: JS has several types of data. What are the basic data types?

Seven data types

  • Boolean
  • Null
  • Undefined
  • Number
  • String
  • Symbol (new in ECMAScript 6)
  • Object

(ES6) before the five basic types: string, number, Boolean, null, and undefined,

The ES6 Symbol is also a primitive data type, representing a unique value

Object is a reference type. It can also include arrays, functions,

Q: nullandundefinedThe difference of

In general, to know why please search the engine

Similarities:

  • inifIn the judgment statement, the value defaults tofalse
  • In general, both represent nothing, depending on the difference

Differences:

  • nullConvert the numeric type value to 0, whereasundefinedConvert the number type toNaN(Not a Number)
  • undefinedIs to call a value that is not assigned, and the default isundefined
  • nullIs a very special object, and the most common use is passed in as an argument (indicating that the argument is not an object).
  • Set tonullWill be collected by the memory collector

Q: DOM operation of JS (Node Node obtaining, adding, deleting, checking and changing);

  • Get (too many, there areDocument. The getElementById ClassName/Name/TagName, or querySelector)

// example

// get Node
var element = document.querySelector('#test');

/ / append
element.appendChild(Node);

/ / delete
element.removeChild(Node);

/ / to find
element.nextSibling // Get the sibling of the element, and get the comment text, whitespace, and so on
element.nextElementSibling  // Equivalent, get the tag (don't get the comment text)

element.previousSibling // Look for a sibling node
element.previousElementSibling

// Changes, such as properties
element.setAttribute(name, value); // Add attributes
element.removeAttribute(attrName); // Delete the attribute

// Insert a DOM(not overwrite: no innerHTML); // Insert a DOM(not innerHTML);
/* 
      
Hello, World
*/
// Take the example above var test = document.createElement('div'); // Create a block-level element test.setAttribute("id"."test"); // Set its ID attribute var span = document.createElement('span'); // Create a span span.innerText = "Hello,world"; // Insert the text content of span test.appendChild(span); // Combine nodes element.appendChild(test); // Append to a node area Copy the code

Q: In Javascript, there is a function that executes an object lookup, but never looks for the prototype. What is this function?

HasOwnProperty, this is more of a way of distinguishing between properties on its own and properties on the stereotype chain.

Q: give aDOMAdd the capture and bubble of the two ways to write the event click, who executes first?

Situation analysis:

  • Have got nodes, priority capture, not just up the bubble looking for
  • If it’s throughnode.addEventListener('event',callback,bubble or capture); Whoever calls first executes first

Stackoverflow has a related discussion:

  • Event listeners registered for capturing phase not triggered before bubbling – why?

Q: Tell me about your understanding of Ajax and the important points to be aware of when using native JS.

Ajax stands for asynchronous javascript and XML for data interaction with the server, making it possible to replace page data without refreshing.

For those points, make a short Ajax request


var xhr = new XMLHttpRequest(); // Declare a request object


xhr.onreadystatechange = function(){
    if(xhr.readyState === 4) {ReadyState 4 indicates that the request has been sent to the server
        if(xhr.status === OK){ // // status 200 indicates that the server returns a success message
            console.log(xhr.responseText); // This is the text returned
        } else{
            console.log("Error: "+ xhr.status); // Throw an error when the connection fails
        }
    }
}

xhr.open('GET'.'xxxx');

// How to set the request header? xhr.setRequestHeader(header, value);
xhr.setRequestHeader('Content-Type'.'application/json');

xhr.send(null); // The get method sends null(or not), and the POST method sends the value



Copy the code

More details can be read here;

  • << Ajax concept by Ruan Yifeng >>
  • <<XMLHttpRequest2 Usage Guide >>

Q: JS implements a closure function, incremented by 1 each time it is called;

The focus here is on closures, function expressions, and IIFE(Execute expressions immediately)


var add = (function() {
  // Declare a variable, which is declared only once because of the return below
  var count = 0;
  return function() {
    return console.log(count++); }; }) (); add();/ / 0
add(); / / 1
add(); / / 2

Copy the code

Q: [‘1′,’2′,’3’].map(parseInt) output what, why?


['1'.'2'.'3'].map(parseInt); // [1,NaN,NaN]

/ / plane analysis

// Map takes three arguments: the array element, the element index, and the original array itself
// parseInt takes two arguments, the element itself and the base
// If you have these two things sorted out,
// ['1','2','3'].map(parseInt); Is equal to the following
['1'.'2'.'3'].map(function(item,index,array){
    return parseInt(item,index); // Is it clear at a glance
});

// parseInt("1",0); = > 1
// parseInt("2",1); => NaN
// parseInt("3",2); => NaN


Copy the code

Q: How to achieve communication between multiple tabs in the browser?

WebSocket, localStorge, and cookies are available.

It is better to use WebSocket if the browser is in non-trace mode, otherwise the function will fail or error will be reported.

Q: How is webSocket compatible with low browsers?

The most common is polling XHR

Q: What is a Window object? What is a document object?

The window object is the window that the browser opens.

The document object is a read-only reference to the HTML document object and a property of the Window object.

Q: the array [‘ 2018-03-05 ‘, ‘2013-06-12’, ‘2019-03-12’, ‘2018-03-05’, ‘2014-02-22’] to heavy and sorting

I’m using a combination of ES6, which is very short code

// It makes sense that a Set has value uniqueness (but not all values, I'll throw out another article later).
// Combine, deconstruct, can be iterable (e.g. arguments/nodelist, etc.) into an array
// Sort passes in a comparison of two values, and returns -1 and 1 because 1 means the number is large (relative),-1 means small (relative), and 0 means equal

let arr = [,new Set(['2018-03-05'.'2013-06-12'.'2019-03-12'.'2018-03-05'.'2014-02-22'])].sort(function(a,b){
  return a<b ? - 1:1; // Return the value in ascending order, descending order change the return value is good. So it's relative
})

/ / / "2013-06-12", "2014-02-22", "2018-03-05", "2019-03-12"]

Copy the code

For those interested in deweighting arrays, check out my hydrology post:

  • JS array deduplicate!! A lame “deep” hydrology

Q: on the array[1, 2, 3, 4, 5, 6, 7, '8', 'a', 'b' and 'z']To order


// We can still use the above principle of sort to get out of order

let tempArr = [1.2.3.4.5.'6'.7.'8'.'a'.'b'.'z'].sort(function(){
  return Math.random() > 0.5 ? - 1 : 1;
})

// There is no standard answer because there is a random number in it
//["6", "z", 3, "b", 5, 2, 7, "8", "a", 1, 4]


Copy the code

Above and this question involves the array order problem, want to know whya-b.a>bThis class can change the sort

Check out zhihu’s discussion on this section: Portal :javascript sort return A-B?

Q: please[1, 10, 11, 1, '- 5, 12, 13, 14, 15, 2, 3, 4, 7, 8, 9]The difference between the maximum and minimum in


// Let's do a crude version, only if we pass in an array that can be implicitly converted to a number
function MaxMinPlus(arr) {
  // Return the difference between the maximum and minimum values
  return Array.isArray(arr) ? Math.max.apply(Math, arr) - Math.min.apply(Math, arr) : console.log('Not an array passed in or unresolvable error')}// The result is 20

// If you want to improve, consider passing a nonarray,
// Pass a string, then cut it into an array...
// Take into account the amount of code

Copy the code

Q: please giveArrayImplements a method that returns duplicate characters (new array) after deduplication.


  var testArr = [1.6.8.3.7.9.2.7.2.4.4.3.3.1.5.3];

  Array.prototype.extraChar = function(){
      var cacheExtraChar = []; // Cache recurring characters
      var that = this; / / this cache;
      this.map(function(item,index){
          // How to understand this code?
          // There is no repetition. // There is no repetition
          // Why do you need to check the cache again to filter multiple writes in the cache array(that.indexOf(item) ! == that.lastIndexOf(item)) && cacheExtraChar.indexOf(item) ===- 1 ? cacheExtraChar.push(item) : - 1;
      });
      return cacheExtraChar;
  }


testArr.extraChar(); // [1, 3, 7, 2, 4]

// If you need to sort again, sort again

[1.6.8.3.7.9.2.7.2.4.4.3.3.1.5.3]
.extraChar()
.sort(function(a,b){return a-b}) // [1, 2, 3, 4, 7]

Copy the code

Q: An array of PARs contains information about multiple people. Each person’s information is provided bynameage({name: 'zhang' age: 15}). Please use JS to achieve the order of age from youngest to oldest;

Var par = [{age: 5, name: 'Joe'}, {age: 3, name: 'bill'}, {age: 15, name: 'Cathy'}, {age: 1, name: 'casual'}] var parSort = par.sort(function(a,b){ return a.age - b.age; })Copy the code

Q: Determine a palindrome string and a string with the same letter but different order

Palindrome string

It’s the same in either order;

A string with the same letter but different order

The strings are the same, but the locations may not be the same, such as abcefd and dCEabf =>return true

The idea of the latter is to use sort to correct the different order

Normal version

// Palindrome, Var isPalindromes = function(params){params = params.tostring ().tolowerCase () return params === params.split('').reverse().join(''); } var isAnagram = function(str1, str2) {str1 = str1.tostring ().tolowerCase ();} var isAnagram = function(str1, str2) {str1 = str1.tostring (). str2 = str2.toString().toLowerCase(); return str1.split('').sort().join('') === str2.split('').sort().join('') }Copy the code

Advanced version: more special characters

If we want to get rid of all non-alphanumeric characters, we need to use re


// Advanced version: isPalindromes('abc_ &b #@a')

var isPalindromes = function(params){
  // The arguments passed in are converted to strings and all lowercase, and the redundant character comparisons are removed
  params = params.toString().toLowerCase().replace(/[\W_\s]/g.' ');
  console.log(params)
  return params === params.split(' ').reverse().join(' ');
}


// I'm not going to be able to do this. // I'm not going to do this. d@ce^abf')
var isAnagram = function(str1, str2)  {
  str1 = str1.toString().toLowerCase().replace(/[\W_\s]/g.' ');
  str2 = str2.toString().toLowerCase().replace(/[\W_\s]/g.' ');
  return str1.split(' ').sort().join(' ') === str2.split(' ').sort().join(' ')}Copy the code

Q: JSString.trim()Methods;

// Native has a trim() method. We're going to simulate one;

String.prototype.emuTrim = function(){
    // This regular expression is easy to understand. It removes the extra space characters from the header and tail
    return this.replace(/(^\s*)|(\s*$)/g.' ');
}


' fsaf fsdaf f safl lllll '.emuTrim();  //"fsaf fsdaf f safl lllll"

Copy the code

Q: JS functions run for a second to print out 0-9; Given the following code

for(var i=0; i<10; i++){// TODO
}

Copy the code
  • solution

// This problem involves scope
for(var i=0; i<10; i++){ setTimeout((function(i){
   return function(){
       console.log(i);
   }
  })(i),1000);
}

Copy the code

When it comes to ES6, it couldn’t be simpler


for(let i=0; i<10; i++){ setTimeout(function(){
       console.log(i);
  },1000);
}

Copy the code

Q: Implement shallow and “deep” copies of an array or object

Shallow copy is to copy all the values belonging to the source object to the new object, without creating a separate memory region for the two.

Deep copies are completely separate memory areas that do not interfere with each other

  • Shallow copy

// This ES5

function shallowClone(sourceObj) {
  // Check whether the passed object type is an object type
  if(! sourceObj ||typeofsourceObj ! = ='object') {
    console.log('You're not passing in an object!! ')}// Determine the type of Obj passed in and assign the corresponding value
  var targetObj = sourceObj.constructor === Array ? [] : {};

  // Iterate over all keys
  for (var keys in sourceObj) {
    // Judge all keys that belong to their own prototype chain, not those inherited (upstream)
    if (sourceObj.hasOwnProperty(keys)) {
      // Copy them one by onetargetObj[keys] = sourceObj[keys]; }}return targetObj;
}

 // ES6 can use object.assign (targeObj, source1,source2,source3) to implement shallow copy of objects


Copy the code
  • Deep copy

// This is done by converting the type to a basic type (string, etc.) instead of a reference type
// The stringify in the JOSN object can serialize a JS object to a JSON string, and parse can deserialize a JSON string to a JS object

var deepClone = function(sourceObj) {
  if(! sourceObj ||typeofsourceObj ! = ='object') {
    console.log('You're not passing in an object!! ');
    return;
  }
  // Turn -> parse -> return one step
  return window.JSON
    ? JSON.parse(JSON.stringify(sourceObj))
    : console.log('Your browser does not support the JSON API');
};



Copy the code
  • Deep copy considerations are actually much more complicated. See zhihu for more details

Q: The understanding of this object

In short: who calls to whom is determined in context at runtime, not at definition time;

To force this, you can use the call,apply,bind, and arrow functions to change the direction of this

This kind of article is too much, search yourself.

Q: I see you said bind, can you simply simulate it with JS?

Function.prototype.emulateBind =  function (context) {
    var self = this;
    return function () {
        returnself.apply(context); }}Copy the code

This implementation is very crude, more detailed, thoughtful (such as parameters processing and so on), Google.

Q: What is the scope of JS? What’s special about it?

A scope is a context that has its own area (such as within a function), where variable declarations are promoted, function declarations are promoted, etc.

Function declaration promotion is better than variable declaration promotion..

There are global scopes and block-level scopes (local, such as with lets or simple curly braces).

Scope affects the orientation of this

Wait for the supplement, WHEN I answer, the interviewer just um.. Yeah, yeah, I don’t know what it is

Q: How to solve cross-domain problems, what are the methods?

I usually use these three, CORS, NGINx reverse proxy, and JSONP

  • jsonpThe SRC attribute of the script tag is used to achieve cross-domain.
  • Nginx reverse proxy: It is mainly usednginx.confWithin theproxy_pass http://xxx.xxx.xxx, will all requests proxy to that domain name, advantages and disadvantages.
  • corsIf the controllability is strong, need to set the front and back end, compatibility IE10+, such as
    • Access-control-allow-origin: foo.example // Whether the subdomain or even the entire domain name or all domain names are allowed to Access
    • Access-control-allow-methods: POST, GET, OPTIONS
    • Access-control-allow-headers: x-pingother, content-type specifies the allowed header field
    • Access-control-max-age: 86400 // Validity period

Q: What happens if you want to carry some authentication information across domains? Such as cookies!

You need to configure header access-control-allow-credentials :true. For details, see the following nginxDemo

Of course, cros configuration is not only these, there are other, specific engine, I think.

What happens if we want to configure CORS with nginx or Express? Let’s do a simple version

  • nginx
location / {
   Check the domain name suffix
    add_header Access-Control-Allow-Origin xx.xx.com;
    add_header Access-Control-Allow-Methods GET,POST,OPTIONS;
    add_header Access-Control-Allow-Credentials true;
    add_header Access-Control-Allow-Headers DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type;
    add_header Access-Control-Max-Age 86400;
}

Copy the code
  • Express, of course, this product also has some other people’s packagecorsMiddleware, more operational,
let express = require('express');
let app = express();

// Set headers for all requests
app.all(The '*', (req, res, next) =>  {
    res.header("Access-Control-Allow-Origin"."xx.xx.com");
    res.header("Access-Control-Allow-Headers"."DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type");
    res.header("Access-Control-Allow-Credentials"."true")
    res.header("Access-Control-Allow-Methods"."PUT,POST,GET,DELETE,OPTIONS");
    next();
});

Copy the code

Some of them are going to fight you. Any other postures besides that? I said an HTML5 postMessage,

Because really unused, just before the time to look up to understand the next, only a general point

This is mostly used for iframe messaging, which has two steps

  • windowOpen an instance and pass a message to an X domain name
  • X domain namemessageEvent to get the delivered message

It’s not that compatible, and it’s vulnerable to CSRF attacks if it’s not well thought out

Q:XSSCSRFHow to prevent

I’m not going to talk about the conceptual stuff here

  • In the prevention of XSS

    • All I can think of is the escape<>The tags that cause the code to run directly.. Polling or regular substitution
      • And the interviewer said it was the least efficient, so I came back and I looked around and I didn’t think there was a better plan, and some of the messages,
    • If it workscookie, is set tohttp-onlyTo avoid client tampering
  • The prevention of CSRF is generally of these types

    • Although the user experience is not good, the verification code can defend against most attacks in many cases
    • validationHTTP RefererField to determine the source of the request
    • tokenEncryption and decryption, this is a very common method nowadays,

Any defense comes at a cost, such as poor experience due to captcha, performance problems due to token abuse, response time due to polling replacement, etc

Q: describe thecookie.sessionStorage.localStorageThe difference..

  • cookie: the size of about 4KB, following the request (request header), will occupy bandwidth resources, but it is used to determine whether the user is online
  • sessionStorageandlocalStorageThe size depends on the browser support, generally 5MB, data only retained in the local, does not participate in the server interaction.
    • sessionStorageThe lifetime of the session is limited to the session, and the stored data is lost when the session is closed.
    • localStorageIt is kept locally. If no one clears it manually, it will always be kept

Q: javascriptHow do you understand the prototype chain?

The prototype chain is a unique mechanism in JS,

All objects have a built-in [[proto]] pointing to the prototype object that created it.

The prototype chain is basically used to implement inheritance

Q: javascriptHow to implement inheritance inside, how to avoid the prototype chain above the object sharing

When I wrote it, I used two scenarios, one for ES5 and one for ES6

  • ES5: Parasitic combinatorial inheritance: Children inherit from their parents by borrowing constructors to inherit properties and prototype chains.

    function ParentClass(name) {
      this.name = name;
    }
    ParentClass.prototype.sayHello = function () {
      console.log("I'm parent!" + this.name);
    }
    function SubClass(name, age) {
      // If you want more than one parameter, you can use apply
      ParentClass.call(this, name);
      this.age = age;
    }
    SubClass.prototype = Object.create(ParentClass.prototype);
    SubClass.prototype.constructor = SubClass;
    SubClass.prototype.sayChildHello = function (name) {
      console.log("I'm child " + this.name)
    }

    let testA = new SubClass('CRPER')

    / / Object. The create () polyfill
    /* function pureObject(o){// define a temporary constructor function F() {} F.prototype = obj; // Return an instance of this constructor. This instance has all the properties and methods of obj. // Because the instance prototype is an obj object. return new F(); } * /

Copy the code
  • ES6: It’s the grammar sugar of ES5, but very readable..
    class ParentClass {
      constructor(name) {
        this.name = name;
      }
      sayHello() {
        console.log("I'm parent!" + this.name); }}class SubClass extends ParentClass {
      constructor(name) {
        super(name);
      }
      sayChildHello() {
        console.log("I'm child " + this.name)
      }
      // Redeclaring the superclass method of the same name will override,ES5 is directly operating on its own prototype chain
      sayHello(){
        console.log("override parent method ! ,I'm sayHello Method")}}let testA = new SubClass('CRPER')

Copy the code

Q: Are you familiar with ES6+? What features have you used?

  • Arrow function
  • Classes and import, export, and inheritance (class/import/export/extends)
  • String template
  • Promise
  • let.const
  • async/await
  • Default parameter/parameter or variable destructor decorators
  • Array.inclueds/String.padStart|String.padEnd/Object.assign

Q: What’s the difference between let and const?

  • letBlock-level scope is generated, no variables are promoted, and cannot be redeclared (but can be reassigned);
  • const
    • Is a constant. If the data type is basic, it is invariable.
    • Reference values can adjust internal values (which may not have been designed properly!

Q: asyncandawaitThe purpose of the?

  • letpromiseAsynchrony becomes synchronous.awaitCan wait untilpromisecompleted

Q: Arrow functionthisPoint to who?

Sure many friends will point to local methods inside!! The answer is wrong,

What the arrow function changes is not to localize this, but to not bind this to it at all;

This is taken from an external parent scope (but not syntactic sugar for regular function)..

Because there’s no support in the arrow function for var self = this or.bind(this).

Q: Have you ever used static methods, static properties, private variables?

The static method, which came out after ES6, has all these features

  • Methods cannot give a reference to this; they can give a direct reference to the class
  • Statics cannot be called by instances, for exampleLet a = new ParentClass => a.sayhello () raise an exception
  • Superclass static method, subclass is notstaticMethod cannot override superclass
  • Static methods can be inherited from subclasses
  • Static properties can be inherited or modified

Look at the following code..


 class ParentClass {
      constructor(name) {
        this.name = name;
      }
      static sayHello() {
        console.log("I'm parent!" + this.name);
      }

      static testFunc(){
        console.log('emm,Parent test static Func')}}class SubClass extends ParentClass {
      constructor(name) {
        super(name);
      }
      sayChildHello() {
        console.log("I'm child " + this.name)
      }
      static sayHello() {
        console.log("override parent method ! ,I'm sayHello Method")}static testFunc2() {
        console.log(super.testFunc() + 'fsdafasdf');
      }
    }
    ParentClass.sayHello(); // success print

    let a = new ParentClass('test');
    a.sayHello() // throw error

    SubClass.sayHello(); Static with the same name can be inherited and overridden

    SubClass.testFunc2(); // Can inherit

    let testA = new SubClass('CRPER');

Copy the code

Private variables can be simulated using WeakMap, semantically underlined, or symbol.

So I just came back to find the relevant information, and found that there is a better simulation scheme, WeakMap;

WeakMap can avoid memory leak. When there is no value reference, the memory register will be automatically reclaimed.


const _ = new WeakMap(a);Value must be an object. There are four methods: delete,get,has, and set

class TestWeakMap {
  constructor(id, barcode) {
    _.set(this, { id,barcode });
  }
  testFunc() {
    let { id,barcode } = _.get(this); // Get the corresponding value
    return{ id,barcode }; }}Copy the code

Of course, you can implement a private variable using Symbol, which is also a good idea

Q: What do you think of Promise? Does it have anything to do with Ajax?

Promises don’t have anything to do with Ajax. They’re created to solve callback hell;

Ajax is usually combined in order to better comb and control the process, here we simply comb..

Promise has three states: Pending/resolve()/reject();

Some small points to note are as follows

  • inPendingWhen changing to one of the other two states, the state cannot be changed..
  • PromisethethenFor asynchrony. Whereas (new Promise()) constructor for synchronization
  • PromisethecatchCan’t catch errors in arbitrary cases (e.gthenThe inside of thesetTimoutInside manually throw oneError)
  • PromisethethenreturnPromise.reject()Will break the chained call
  • PromisetheresolveValue penetration occurs if a value is passed in instead of a function
  • Promisethecatchorthen.returnAll is a new onePromise(if the Promise has not been interrupted)

Promise also has some built-in methods, such as race,all, which return when either of them is resolved, and all, which returns when all of them are resolved.

Implement a promise function that is delayed with async and await


const delay = (time) = > new Promise((resolve,reject) = >{
  setTimeout(resolve,time)
})


// test

let testRun = async function(){
   console.log(1);
   await delay(2000);
   console.log('I have two seconds to trigger.'.3)}// 1 => Promise = > 3



Copy the code

What is the result of running this code?

var test = new Promise((resolve,reject) = >{
   resolve();
});

test
  .then(data= > {
    // promise start
    console.log('promise first then : ', data);
    return Promise.resolve(1); // p1
  })
  .then(data= > {
    // promise p1
    console.log('get parent(p1) resolve data : ', data);
    return Promise.reject(new Error('Oh, it's broken. What can you do? ')); // p2

  })
  .then(data= > {
    // promise p2
    console.log('result of p2: ', data);
    return Promise.resolve(3); // p3
  })
  .catch(err= > {
    console.log('err: ', err);
    return false;
  });

// promise first then : undefined
// get parent(p1) resolve data : 1
// err: Error: No, I'm not.

// Here the chained call is broken when then returns promise.reject (). Catch directly to catch



Copy the code

Don’t worry, what if you execute a callback function at the end regardless of whether or not an error was caught?

This means something like try.. catch.. Finally, give Promise a finally;

// In the end, in the end, in the end, in the end, in the end
// url : https://www.v2ex.com/t/205715
//1. No arguments are accepted. The original value or Error cannot be received in the finally
//2. The processing does not affect the state of the original Promise, whether it is REJECT or reject or resolve
//3. The resolve state still passes the original value, and the Reject state still passes the original Error

Promise.prototype.finally = function (callback) {
  let P = this.constructor; // This is the constructor for Promise

  This will be fulfilled someday. This function will be fulfilled someday.
  return this.then(
    value= > P.resolve(callback()).then((a)= > value),
    reason => P.resolve(callback()).then((a)= > { throw reason })
  );
};

// You can simply pass in a callback function...
// https://developers.google.com/web/updates/2017/10/promise-finally
// This url indicates which versions of Node and Chrome have implemented finally and its usage
// ES 2018 has finally appended to the promise prototype chain...


Copy the code
  • < >: help you more profound understanding of the Promise operation
  • 9 Tips about Promise
  • For more details, see <

    >;

Q: Tell me about your understanding of TCP.

Q: TCP is at which OSI layer! Is the communication process full duplex or half duplex (simplex)?

A: Transport layer, full duplex

Q: What is the process of TCP communication?

A: The whole process is three handshakes, four waves..

Q: You’re right. What about the whole process?

A: For example, I compare TCP to two people talking on A walkie-talkie… Three handshake is it.A1(the snarler, the client) wants to call A2(the server in the control room)..

A1 says on the intercom, “Over over, hear, please.”

A2 Received response “received received, you say “(second, confirm the response)

A1 starts blah blah blah and A2 doesn’t say no (third time, communication set up)

And the four waves are the two to confirm the completion of the confessions to each other.

A1 says, “Control room, report done “(first wave)

A2 says :” I see, then just finish your nonsense and listen to me. Blah blah blah…” (Second wave)

A1 Wait for the control room to finish speaking, and the control room waits for the response (third wave)

By the time A1 feedback to the control room is confirmed, all know.. (the fourth wave),

The above is all nonsense, there may be some places to describe the wrong, just laugh

TCP does not establish 100% success, will cause the link failure of many cases..

Such as a long time no response (A1 roar for a long time no response or A2 answered and A1 no longer bird it).. Or lose a packet (and a walkie-talkie);

TCP protocol related articles on the Internet many, if you want to more comprehensive understanding of the protocol please own engine..

I suggest reading <

>, this is the Web bible, very thick, I only read a few bits..

Q: You know about TCP, so you know about the OSI layer 7 protocol and the OSI Layer 5 network architecture.

For this kind of problem I can only point in general, after all, not specializing in the network piece,

The seven OSI layers include the physical layer, data link layer, network layer, transport layer, session layer, presentation layer, and application layer.

The five-layer model is the session, presentation, and application layer.

Q: Do you know the general execution process of DNS? Which level does it belong to? At what level do you work?

DNS belongs to the application layer protocol, as for TCP/UDP which layer to run, depends on the situation, the general execution process is like this;

The default DNS port is 53

  1. Read the browser cache first
  2. Secondly, the system cache
  3. Are not the case, look for localhostsFiles (such as if you wrote mapping to find first)
  4. Find the nearest DNS server if there is no more
  5. No more will expand access, and eventually find the root server, or did not fail..

There are several record types that need to be understood for DNS resolution:

  • A: Domain name directly to IP
  • CNAME: Multiple domain names can be mapped to a host, as inGithub PageJust useCNAMEPoint to the
  • MX: Mail exchange records, not much used, generally used to build the mail server
  • NS: Parses service records. You can set weights and specify who parses them
  • TTL: Specifies the time to live (also known as cache time). Most domain name resolvers have a default value, or you can set it manually
  • TXT: Indicates the description of a host name or domain name

Come back and I will find the relevant information, interested in further understanding, the portal is as follows:

  • Sort out the OSI layer 7 network and TCP/IP Layer 5 network architecture in Linux
  • TCP/IP (6) Application layer (DNS and HTTP protocol)
  • DNS domain name resolution anatomy

Q: What is the difference between HTTP and HTTPS? Have you heard of SPDY?

I just gave you a rough answer,

Compared with HTTPS, HTTP is faster and less expensive (without SSL/TSL). The default port is 80.

HTTP is susceptible to domain name hijacking, whereas HTTPS is relatively secure (encrypted) and has a default port of 443.

HTTP is plain text running over TCP. Whereas HTTPS runs below the SSL/TLS application layer, on TCP

Q: How does TLS/SSL in HTTPS protect data?

There are generally two forms of asymmetric encryption, generate public and private keys, private key lost server, public key every request to compare authentication;

Certificate Authority (CA) is more strictly adopted to sign the key.

Q: When you talk about symmetric and asymmetric encryption, can you tell us how the whole process works? (HTTPS)

  • Symmetric encryption:
    • Both parties have the same key, each communication to generate a unique key, very fast
    • Security is low and the number of keys grows extremely fast
  • Asymmetric encryption (usually RSA)
    • High security, high resource consumption (CPU), the current mainstream encryption algorithms (mainly for the exchange of keys or signatures, not all communication content)
  • CA(digital signature):
    • This was created to prevent middlemen from stealing data
    • Use some algorithm issued by the authority to sign, the authority as a middleman, the communication process will be checked with the agency

Know really not much, came back to find the relevant information, interested can click to see;

  • An in-depth look at HTTPS security issues & the whole connection setup process
  • In-depth understanding of HTTPS communication encryption process: “colloquial” : read the above article to see the following, will be much clearer

Q: SPDY? What’s it from?

Google is pushing a protocol (HTTP over SSL [TCP]), which is sort of a precursor to HTTP2, with all these advantages

  • Compressed data (HEADER)
  • multiplexing
  • Priority (you can set the priority for the request)

HTTP2 inherits most of these advantages…

Q: Do you know anything about the status of HTTP?

Here is a common list of…

  • 1XX: Generally used to determine the protocol change or confirm the server received the request
    • 100: The server receives part of the request and can continue to deliver the following content if it does not reject the request
    • 101: Client requests to change protocol, server receives acknowledgement
  • 2xx: request succeeded, link created or not, request accepted or not, content or not
    • 200: (Success) The server successfully processed the request.
    • 201: (created) The request was successful and the server created a new resource.
    • 202: (accepted) The server has accepted the request but has not yet processed it.
    • 204: (no content) The server successfully processed the request but did not return any content.
  • 3XX: Used to determine redirection and cache
    • 301: All requests have been moved to a new URL (permanent redirect) and will be cached
    • 302: temporary redirection, not cached
    • 304: Local resources have not been changed. Local resources are preferred (according toIf-Modified-Since or If-MatchTo compare server resources, cache)
  • 4XX: Generally used to confirm authorization information, whether the request is wrong, whether the page is lost
    • 400: request error
    • 401: Unauthorized access to certain resources
    • 403: Blocking access, usually also a permission issue
    • 404: Page missing, resource not found
    • 408: The request times out
    • 415: The media type is not supported, the server will not accept the request.
  • 5XX: Basically, errors on the server
    • 500: server error
    • 502: Gateway error
    • 504: The gateway times out

Q: What about HTTP request packets? Can you give a general description?

HTTP request packet = request line + request header + request body;

  • Request line: this easy to understand is the method of access + protocol + access URL composition
  • Request header: This is understandable, for exampleaccept.content-type.user-agentThis type of value key pair can be read directly by the server
  • Request body: for example, a form submitted by POST, which we encode and place on top of to be passed

Want to learn more about specific engine search

Q: Yes, the request message. How does the cookie follow the request?

A Cookie is stored in the HTTP request or response header (the Cookie is generated by the server) and travels along the way,

Q: What Cookie quarantine is and how to do it;

Cookie isolation is to reduce the data contained in the header in order to speed up access

Solution: Static resources lost CDN or non-primary domain to load

Q: What do you know about browser caching and server caching control?

  • Last-Modified:
    • The resource pulled from the server on the first request automatically carries this property
    • The second request will be compared to the serverIf-Modified-SinceIf no change is made, use local (state 304)
    • In combination withExpires(Expires time: when the cache Expires), sent along with the request.. Resource not expired take local, otherwise re-request
  • Cache-controlHTTP1.1The combination of things to judge resource expirationmax-ageTo replace theExpires [HTTP 1.0]
  • Etag:
    • The first time a URL is requested, the server is tagged (a string of characters)
    • The second request will be compared to the serverIf-None-Match, still take cache (304)

Q: A few short questions that impressed me

if(! ("a" in window)) {var a = 10;
}
console.log(a); // undefined

/ /! ("a" I n window), returns true
/* var a; if(! ("a" in window)){ a = 10; } * /

/ / variations
(function(){
 var  x = c =  b = {a:1}
})()

console.log(x.a); // error , x is not defined
console.log(c,b) // {a: 1} {a: 1}


Copy the code
var count = 0;

console.log(typeof count === "number"); // This is true

console.log(!!typeof count === "number"); // false

// There are priorities and Booleans involved
// Typeof count is the string "number"
/ /!!!!! Is converted to a Boolean (a variant of the ternary operator), a non-empty string Boolean to true
True === "number", return false

Copy the code

(function(){
  var a = b = 3; }) ()console.log(typeof a === "undefined"); // false
console.log(typeof b === "undefined"); // false

// There are immediate execution and closure issues, variable promotion, operator execution direction (= sign from left to right)
// The function can be broken down like this

(function()
  var a; /* Local variable, not externally accessible */b= 3; /* Global variables,so . window.b=== 3. */ can be accessed externallya = b; }) (// If this is the case, the problem should be correctconsole.log(typeof b === "number" && b ===3
); // true


Copy the code

function foo(something){
  this.a = something;
}

var obj1 = {
  foo:foo
};

var obj2 = {};

obj1.foo(2)

console.log(obj1.a) // 2, the this context is still in obj1, or window if obj1.foo is saved as a reference before being passed

obj1.foo.call(obj2,3); // Use call to force change context to obj2
console.log(obj2.a); / / 3

var  bar = new obj1.foo(4); // An instance is generated here
console.log(obj1.a); / / 2
console.log(bar.a); / / 4. The binding of new takes precedence over implicit and explicit bindings


Copy the code
function fn(){
 alert(a);
 var a = 200;
 alert(a);
}

fn(); // undefined / 200 ; Promotion of involved variables
alert(a); // undefined
var a;
alert(a); // undefined

var a = 300;
alert(a); / / 300

Copy the code
var obj1= {
  name:'obj1'.fn:function(){
    console.log(this.name); }};var obj2 = {name:'obj2'};
var obj3 = {name:'obj3'};

// This is the most important thing in the world.
obj1.fn(); // obj1

var newFn = obj1.fn;
newFn(); // Undefined, this refers to window

newFn.call(obj2);// obj2, this points to obj2

obj3.fn = newFn;
/ * ƒ () {the console. The log (enclosing name); } * /

obj3.fn(); // This refers to obj3. Output obj3




Copy the code

// This question is very difficult to write as a test, because there are many answers to answer. Anyway, I did meet...
// This question is mainly concerned with understanding the inheritance part of the prototype chain
function Parent(){
  this.a = 1;
  this.b = [1.2.this.a];
  this.c = {demo:5};
  this.show = function(){
   console.log(this.a + ' ' + this.c.demo + ':' + this.b)
  }
}

function Child(){
  this.a  = 2;
  this.change = function(){
    this.b.push(this.a);
    this.a = this.b.length;
    this.c.demo = this.a++;
  }

}

Child.prototype = new Parent();
var parent = new Parent();
var child1 = new Child();
var child2 = new Child();

child1.a = 11;
child2.a = 12;

// The first few are easy, continue to read
parent.show(); / / now, 2, 1

// Since the Child itself does not have a show method, look up the prototype chain;
// Find the parent class,this has not changed, so the output is as follows
child1.show(); / / 115:1, 2, 1
child2.show(); / / 125:1, 2, 1

child1.change();  // Change some data, no output
child2.change();  / / + 1

parent.show(); / / now, 2, 1

child1.show(); / / thyself, 2,1,11,12
child2.show(); ,2,1,11,12 / / 65:1

Copy the code

// The function is called recursively


function test(a,b){
  console.log(b);
  return {
    test:function(c){
       returntest(c,a); }};// It is easy to understand this problem
/*function test(a,b){ console.log("a:"+a,"b:"+b); return { test:function(c){ console.log("a:"+a,"b:"+b,"c"+c); return test(c,a); }}} * /



var a = test(100); // Undefined, this is self-evident;
a.test(200); //  100;
a.test(300); / / 100;

var b =  test(101).test(201).test(301); // undefined/101/201


var c =  test(102).test(202); // undefined / 102

c.test(302); / / 202


Copy the code

Var test=’abc345efgabcab’; Meet the requirements as prompted

  • Remove the a, B,c characters from the string to form the result ‘345efg’;

test.replace(/[abc]/g.' '); // "345efg"

Copy the code
  • Put the numbers of the string in parentheses to form the result: ABC [3][4][5]efg,.’

test.replace(/\d/g.'[$&]');  // "abc[3][4][5]efgabcab"

// If there is a group, the reference is in the form of $1, $2, $3, and $& represents the entire match of the regular expression.

Copy the code
  • Multiply the value of each number in the string by 2, and output :’abc6810,.’

var temp = test.split(' ').map(function(item){
  return /^\d$/.test(item) ? item * 2 : item;
}).join(' ');

// "abc6810efgabcab"



Copy the code

Q: Replace text in at least three ways"dream"to"package"To provide a string"I have a dream";

  • Regular replacement
// This is the simplest amount of code...
var str = "I have a dream";
str.replace(/dream/g."package");

// You can replace the string without the re
str.replace("dream"."package")

Copy the code
  • Array traversal changes
// Very straightforward brain circuit
var str = "I have a dream";

str.split("").map(function(item){
 return  item === "dream" ? item = "package":item;
}).join("");

Copy the code
  • Array query cutting method
var str = "I have a dream";

var tempArr = str.split(""); // ["I", "have", "a", "dream"]
var removeIndex = tempArr.indexOf('dream'); / / 3

tempArr.splice(removeIndex,1."package");

var transStr = tempArr.join(""); // "I have a package";

Copy the code

It’s easy to make arrays of these things

This is the message area friends provide method.. Similar, as follows;


/ / the source code
// String also has array slice and concat methods... The idea is similar to arrays
var str = 'I haved a dream';
str.indexOf('dream')! = =- 1 ? str.slice(0,str.indexOf('dream')).concat('package'):str;



Copy the code

Q: There is also a question involving event loops, executing priority..

Macrotask: Microtask: Macrotask: Microtask: Macrotask: Microtask

To say why, to show a face, came back to find the relevant information;

  • The Event Loop is an Event Loop
  • In-depth understanding of event loops and asynchronous process control
  • Everything you need to know about fully understanding the Node.js event loop and its metrics

Q: How well do you know the basic algorithms?

Here, here’s the paper. Try a quick row.


// The general idea of quicktype is:
// Find the median value and cut it from the original array,
// Keep the rest as two arrays and compare them each time;
// Until the recursion results, the average complexity is O(nlog n).

function quickSort(arr) {
  // If the length of the array is <=1, return it directly
  if (arr.length <= 1) {
    return arr;
  }
  // The middle bit (reference) is rounded down by half of the length
  var pivotIndex = Math.floor(arr.length / 2);
  // Splice will change the array!!!!
  var pivot = arr.splice(pivotIndex, 1) [0];
  // Define two empty arrays to hold the compared values
  var left = [];
  var right = [];

  // Put the smaller ones on the left and the larger ones on the right
  for (var i = 0 , j = arr.length; i < j; i++) {
    if (arr[i] <= pivot) {
      left.push(arr[i]);
    } else{ right.push(arr[i]); }}Arr = [left, pivot, right]
  // Select * from array; // Select * from array; Until finally there's nothing left to cut
  return quickSort(left).concat([pivot], quickSort(right));
}

Copy the code

Q: Write a dichotomy search

/ / dichotomy with fast line of thinking about, binary comparison / / this is only used to sort an array in the query, hi-lo know function under the condition of binSearch (target, arr, start, end) {var start = start | | 0; / / allow what position from the start, the subscript var end = end | | arr. Length - 1. // Start >= end? 1: "'; Var mid = math.floor ((start + end) / 2); If (target == arr[mid]) {return mid; } else if (target > arr[mid]) {return binSearch(target, arr, start, mid-1); Return binSearch(target, arr, mid + 1, end); else {// Return binSearch(target, arr, mid + 1, end); }} / / binSearch (5,,2,3,4,5,6,7,8 [1]) = > 4 / / chaotic array need to sort an array, otherwise it will stack overflow (infinite loop)Copy the code

There are many articles in this category, and those who are interested can read some articles below

Portal:

  • << Top 10 Sorting algorithms summary (JavaScript description >>)
  • JavaScript data structures and algorithms
  • Javascript common sorting algorithm

Q: What do you know about design patterns?

  • A detailed explanation of common Javascript design patterns
  • js-design-pattern

Q: You have two glass balls, and there is a 100-meter tall building. Ask which floor will break the glass balls when you drop them.

The main point of the problem: glass ball broken (finite number), determine the number of floors, the least number => is to find the optimal formula

In this problem to show a face, my first train of thought

If you fold it in half, it becomes [1-50][51-100], so 1+50 = 51 times,

The interviewer says that if you use a quick list of ideas, it is definitely not the best.

Hold for a long time, thought of the square rootIn this case, only 20 times at most

And then he said give me three balls, at 1,000 meters, how many times, but according to me above,

Open a party,No more than 30 times;

As for how to determine the position of the first drop, it is the value after the draw as an interval.

If there are N balls and M meters, the height range for the first drop is this

The interview boss said this is ok, then leave it

, came back with the omnipotent search engine to find the next.. There’s a lot of things to think about. It’s not that simple

Portal: Someone discussed this issue on Zhihu;

But high number returned to the teacher.. This kind of post see a face meng force, take time to study again

Q: How much do you know about optimization?

General common means to understand.

Client start

  • Compress the code (JS/CSS), compress the image
  • Merge some small images (css sprite)
  • If the code is packaged, cut it as many as possiblechunk, reduce singlechunkToo much
  • Static files are imported using CDN
  • HTTP cache headers are used reasonably
  • Reduce dependencies on third-party libraries
  • Code should be written for performance, such as userequestAnimationFrameDraw animations to minimize page redraws (DOM changes)
  • Gradual upgrade, introductionpreloadThese preload resources
  • Look at the situation withservice workerTo cache resources (e.g. mobile is going to do PWA)

Server start

  • Bandwidth, domain name resolution, multi-domain name resolution, etc
  • Pages rendered on the server, reducing dependency on the browser (no client parsing)
  • Incremental upgrades, such as the introduction of HTTP2(multiplexing, header compression, etc., can significantly speed up loading)

Of course, these are very one-sided points, the actual work to carry out is much more complex;

For example, we need to consider multiple dimensions, to optimize the DOM drawing time, resource loading time, domain name resolution and so on;

To fully optimize a project is a big project,

Q: What index types does MySQL have? How is the index data structure stored? Differences between MySQL and MongoDB

MySQL index type:

  • Ordinary index: for ordinary types
  • Unique index: indicates that the value of the index is unique and not repeated (null values are allowed)UNIQUE
  • Primary key index :(create table following create, unique index, do not allow null value)
  • Composite indexes (that is, create multiple fields into a single index)

Indexes have both advantages and disadvantages. If used well, the query speed will be accelerated. If the index is abused, the disk space will be occupied and the maintainability will be increased. Indexes do not contain null columns;

I have only briefly learned about b-Tree index data structure storage

As for the differences between MySQL and MongoDB;

The former is a relational database, while the latter is a non-relational database (data is stored in the form of documents, and the value is key-value).

MySQL has a wide range of applications, such as transaction systems, linked list queries, which are very convenient. It is often the workhorse database for many systems

As NoSQL, MongoDB is not as good as MySQL in some aspects, but it is also widely applied, such as the maintenance of some users’ summary information and some cache information combined with the front-end.

Em,. Back-end understanding is not much, also can point to namely stop,. University of time learned some.. Almost all back to the teacher.

Q: JS time segments

Given a time range and step size, enumerate the division of step size within the time range

For example, from 3:00 to 5:00, the step length is 20 minutes

So the returned array is

[‘ 3:00 3:20 ‘, ‘the man – 3:40 p.m,.] and so on

This kind of problem, generally must first sort out the train of thought to write;

  • Given a string period, cut, convert to minutes
  • Trans-day and trans-time problems

// My little friend also wrote this thing. Mine is to annotate the way it is solved and to consider the judgment of parameters
/ / the solution to his plan on his making https://github.com/lyh2668/blog/issues/1, by lyh2668
// The following code contains the ES6 pose (default value, haircut function)

let inputDateRange = (date, step = 30, separator = The '-') = > {
  let startTime, endTime; // Start time and end time

  if (Object.prototype.toString.call(date) === '[object String]') {
    date = date.trim(); // Remove the Spaces on both sides
    var tempDate = ' ';
    if (separator) {
      tempDate = date.split(separator);
    } else {
      if (date.indexOf(The '-')! = =- 1) {
        tempDate = date.split(The '-');
      } else if (date.indexOf('~')) {
        tempDate = date.split('~');
      } else {
        console.log('You may not be passing in a time period!! ');
      }
    }
    startTime = time2min(tempDate[0]); // The incoming start time
    endTime = time2min(tempDate[1]); // The end time passed in
  } else if (Object.prototype.toString.call(date) === '[object Array]') {
    if (date.length === 2) {
      startTime = time2min(date[0]); // The incoming start time
      endTime = time2min(date[1]); // The end time passed in}}else {
    console.log('You may not be passing in a time period!! ');
  }

  // If the step passed in is numeric, otherwise the screenshot will be converted to numeric parts
  // When comparing NaN (with its own inequality), if the re passed in is not recognized, the default value should be given
  Object.prototype.toString.call(step) === '[object Number]'
    ? (step = parseInt(step, 10))
    : parseInt(step.replace(/[W\s\b]/g.' '), 10) = = =NaN
      ? (step = parseInt(step.replace(/[W\s\b]/g.' '), 10))
      : (step = 30);

  // If the start time is longer than the end time, add one day to the end time
  startTime > endTime ? (endTime += 24 * 60) : ' ';

  let transformDate = []; // Store the converted array in time segments

  // Start the iterating judgment, using while
  while (startTime < endTime) {
    // If the start time + step is larger than the end time, then the segment ends. Otherwise, the end time is incremented by the step
    let right = startTime + step > endTime ? endTime : startTime + step;
    transformDate.push(`${min2time(startTime)}-${min2time(right)}`);
    startTime += step; // Step size increments
  }
  return transformDate;
};

// Convert time to minutes
let time2min = time= > {
  // Get the cut
  time.indexOf(':')? (time = time.trim().split(':')) : ' ';
  return time[0] * 60 + parseInt(time[1]); // Return the minutes of conversion
};

// Minutes transfer string time
let min2time = minutes= > {
  let hour = parseInt(minutes / 60); // Return how many hours
  let minute = minutes - hour * 60; // The number of minutes left after deducting hours

  hour >= 24 ? (hour = hour - 24) : ' '; // If the value is greater than or equal to 24 hours, subtract one day to get the remaining hours
  minute < 10 ? (minute = '0' + minute) : ' '; // If less than 10, add zero
  hour < 10 ? (hour = '0' + hour) : ' '; // If less than 10, add zero
  return `${hour}:${minute}`;
};


// test, which supports string passing time range
inputDateRange('3:00 to 5:00'.'20d'); / / [" 03:00-03:20 ", "03:20-03:40", "03:40-04:00", "04:00-04:20", "04:20-04:40", "04:40-05:00"]

// Or an array is passed in
inputDateRange(['3:00'.'5:00'].'45df.3d'); / / [" 03:00-03:45 ", "03:45-04:30", "04:30-05:00"]

// Step supports digits or digits with special characters
inputDateRange(['6'.'8'].'55df.3d'); / / [" surf - 06:55 ", "06:55-07:50", "07:50-08:00"]

inputDateRange('3:00 to 5:00'.60); / / [" 03:00-04:00 ", "04:00-05:00"]


Copy the code
  • JS unreliable series enumerates the time period and the corresponding number of minutes

Q: Vue-RouterWhat do the two modes of the

  • hashMainly depends onlocation.hashTo change the URL, to achieve the effect of not refreshing the jump. Every timehashChange triggershashchangeEvents (to respond to routing changes, such as page changes)
  • historyMainly utilizeHTML5thehistoryAPI to do thatpushStateandreplaceStateTo manipulate the browsing history stack

Q: What are the differences between MVVM and MVC? Heard of the MVP?

There are many articles of this kind, the birth of the three development modes have before and after, not at the same time.

Portal:

  • Diagrams of MVC, MVP and MVVM
  • Brief analysis of MVC/MVP/MVVM model in front-end development

Q: Find all the “daffodil” numbers between 100 and 999, which is the sum of the cubes of each of the three digits equal to itself153 = 1 5 ^ ^ 3 + 3 + 3 ^ 3

  • Conventional traversal
function threeWaterFlower(rangeStart, rangeEnd) {
  var temp = [];
  rangeStart = rangeStart || 100;
  rangeEnd = rangeEnd || 999;
  for (var i = rangeStart; i <= rangeEnd; i++) {
    var t = i.toString().split(' ');
    Math.pow(t[0].3) + Math.pow(t[1].3) + Math.pow(t[2].3) == i
      ? temp.push(i)
      : ' ';
  }
  return temp;
}


threeWaterFlower(100.999); // [153, 370, 371, 407]

threeWaterFlower(); // [153, 370, 371, 407]


Copy the code
  • Extended writing method,ES6 version + indefinite number of flowers, do not toss uncomfortable version

let manyWaterFlower = (rangeStart = 100, rangeEnd = 999, flower = 3) = > {
  let temp = [];
  for (let i = rangeStart; i <= rangeEnd; i++) {
    let t = i
    .toString()
    .split(' ')
    .map(item= > Math.pow(item, flower))
    .reduce((cur,next) = > parseInt(cur)+parseInt(next));
    let transformT = parseInt(t, 10);
    transformT == i ? temp.push(i) : ' ';
  }
  return temp;
}

manyWaterFlower(); // [153, 370, 371, 407]

manyWaterFlower(100.10000.4); / / [1634, 8208, 9474]

manyWaterFlower(100.10000.5); / / [4150, 4151]


Copy the code

This is the exhaustive traversal, if you want to be faster (consider a bit more comprehensive), and pass the scope of correction

I believe that everyone can understand, I have tried to annotate..


let manyWaterFlower = (flower = 3,rangeStart, rangeEnd ) = > {
  let temp = [];// Cache all found flower values

  // This section is the start of the loop to fill the range, after the processing is completed into a number, the recommended starting value
  let flowerRecommandStart = Number(
    ' '.padStart(flower, '0').replace(/^(\d{1})/g.'1'));let flowerRecommandEnd = Number(' '.padStart(flower, '9'));

  // Check whether the start value is passed in
  if (rangeStart) {
    rangeStart > flowerRecommandStart
      ? (rangeStart = flowerRecommandStart)
      : rangeStart;
  } else {
    rangeStart = flowerRecommandStart;
  }

  // Check whether an end value was passed in
  if (rangeEnd) {
    rangeEnd > flowerRecommandEnd ? (rangeEnd = flowerRecommandEnd) : rangeEnd;
  } else {
    rangeEnd = flowerRecommandEnd;
  }

  // If the initial value is greater than the end value
  if (rangeStart > rangeEnd) {
    rangeEnd = flowerRecommandEnd;
  }

  for (let i = rangeStart; i <= rangeEnd; i++) {
    let t = i
      .toString()
      .split(' ')
      .map(item= > Math.pow(item, flower))
      .reduce((cur, next) = > parseInt(cur) + parseInt(next));
    let transformT = parseInt(t, 10);
    transformT == i ? temp.push(i) : ' ';
  }

  return temp;
};

console.time('manyWaterFlower');
manyWaterFlower(4)
console.timeEnd('manyWaterFlower');
// vm34013:4 manyWaterFlower: 8.112060546875ms, this is the time to run outThe code from the example above100to9999Yes, let's take a runconsole.time('manyWaterFlower');
manyWaterFlower(100.9999.4)
console.timeEnd('manyWaterFlower');
/ / VM3135:4 manyWaterFlower: 10.51904296875 ms


// My MBP is stuck at 10, 7 is a bit too long,
console.time('7 flower')
manyWaterFlower(7);
console.timeEnd('7 flower')
/ / 7 flower: 6489.608154296875 ms

// 8 Spend the CPU fan screaming,.
console.time('8 flower')
manyWaterFlower(8);
console.timeEnd('8 flower')
// VM644:3 8 flower: 68010.26489257812ms

// We haven't considered the overflow problem yet. Because the range of positive integers in JS is finite.
// If you are interested, you can improve it by yourself

Copy the code

Q: Please use the recursive algorithm to find the corresponding value in the JSON object through the node key array after TODO annotation

Such as the console. The log (findNode ([‘ a1 ‘, ‘b2], data)) = = = data. A1, b2

// Use the recursion algorithm to find the corresponding value in the JSON object through the node key array after TODO annotation

var data = {
  a1: {
    b1: 1.b2: 2.b3: {
      b4: 5}},a2: {
    b1: 3.b2: 4}};function findNode(inPath, inData) {
  // TODO

  // Check whether an array is passed in
  if (Array.isArray(inPath)) {
    // If the key has a value of 1, return -1 if it has a value, return -1 if it has no value
    if (inPath.length === 1) {
      return inData[inPath[0]]? inData[inPath[0]] :- 1;
    }else{
     return findNode(inPath.slice(1), inData[inPath[0]]); }}else{
    console.log('You are not passing in an array')}}console.log(findNode(['a1'.'b2'], data)); / / 2
console.log(findNode(['a1'.'b3'.'b4'], data)); / / 5


Copy the code
  • An extended version? Supports passing strings or arrays;findNode('a1.b2',data)?

var data = {
  a1: {
    b1: 1.b2: 2.b3: {
      b4: 5}},a2: {
    b1: 3.b2: 4}};// Determine the format
function isType(params) {
  let type = Object.prototype.toString.call(params);
  if (type === '[object String]') {
    params = params.split('. ');
    return params;
  }
  if (type === '[object Array]') {
    returnparams; }}function findNode(inPath, inData) {
  inPath = isType(inPath);
  // Check whether an array is passed in
  if (Array.isArray(inPath)) {
    // If the key has a value of 1, return -1 if it has a value, return -1 if it has no value
    if (inPath.length === 1) {
      return inData[inPath[0]]? inData[inPath[0]] :- 1;
    }else{
     return findNode(inPath.slice(1), inData[inPath[0]]); }}else {
    console.log('You are not passing in an array'); }}console.log(findNode(['a1'.'b2'], data)); / / 2

console.log(findNode('a1.b3.b4', data)); / / 5



Copy the code

Q: What is Webpack? What are the common optimization methods for WebPack?

Webpack is a resource processing tool that saves us manpower and time; You can package resources, parse them, differentiate development patterns, and so on,

Common optimization methods:

  • Separate third-party libraries (dependencies), such as importsdll
  • Introduce multi-process compilation, such ashappypack
  • Extract common dependency modules, such ascommonChunkPlugin
  • Resource obfuscation and compression: for exampleUglifyJS
  • Separate the styles and all that, and reducebundle chunkThe size of, for exampleExtractTextPlugin
  • GZIP compression, in the packaging of resources aligned compression, as long as the deployed server can resolve. Reduce the size of the request
  • As well as load on demand, the general mainstream framework has the corresponding module lazy loading mode.
  • As for thetree shakingCurrently, WebPack 3/4 is integrated by default

Q: The general process from when you enter a URL to rendering the page,

The general process is like this, want to know very detailed can own engine;

  1. IP->DNS(browser => system cache =>DNS server)-> domain name resolution
  2. TCP protocol completion ->HTTP(S) protocol -> Cache ->(Analyze request header)-> Feedback packet
  3. Request document down ->CSSDOM-> static resource download ->render(document)-> JS parse
  4. The user sees the page

Q: What are the means of communication of Vue components?

  • Father – > the son:props
  • Children – > father:on+emit
  • Father: < > the sonon.syncSugar
  • Brother:event bus | vuex

Q: VuexWhat do you think?

Vuex is a state management container (which you can also think of as a global variable), and the flow of data is one-way,

And the data is not persistent (by default, all states are reset when refreshed);

Some of the data and methods in it can be roughly understood as some of the features of VUE, such as

Vuex Vue
state data
getter computed
mutation/actions methods

What about one-way data flow (global singleton pattern)

State can only make changes to the mutation, action can only feed back to the mutation, can perform asynchronous operations (such as interacting with the backend to pull data), State can trigger render,action can dispatch.. As shown in figure

conclusion

There are some questions can not remember, there is no way, there are some questions are to see your personal play, can not write, such as

  • Q: If you were asked to do the technical selection for a company project, what would you do and why?
  • Q: React.Angular.VueThe comparison?
  • Q: Tell me about itVNodeUnderstand it,diffIn the process;
  • Q: VueHow bidirectional binding is implemented, what pattern is used (subscription pattern), and how it is implemented in general.
  • Q: cmd/amd/commonjsThe difference of
  • Q: Small programs andReact NativeThe difference.. , etc.

The process of the interview bumps and bumps to find their own many shortcomings and need to work in the direction.

If there is any mistake, please leave a message. We will follow up and correct it in time. Thank you

Gold mining technology article request activity link: juejin. Im /post/1