preface

The author has two years of front-end experience, and has met with many companies for about one month, such as Like, Doodle Intelligence, Didi, Byte, Kukler, Hikvision, Tax Friend, etc., to sort out some questions (including but not limited to) that I was asked during my personal interview.

Before you start interviewing, a good resume is also very important, recommend two articles: what a good front-end development engineer resume, how to write a “front-end resume”, can knock on the door of Bytedance?

In order to get a more satisfactory offer, I chose some small and medium-sized companies to practice my hands in the previous week. Later, I found that there was no effect of training in small companies, so A week later, I began to send my resume to large factories.

What impressed me most was Kujialer. One side was remote, and then the second interview was on the spot. The scene consisted of three rounds of technology + HR, which was almost three hours, which was very efficient. It’s also highly efficient. The interview process is the same as that of Kukla, which is remote one side, three rounds of technology + HR on-site. Other companies are basically round by round, the results of each round will inform you the next day, of course, if the next few days can not wait, is also a kind of notification.

HTTP

HTTP questions are hot interview questions, in some cross surface or side of the inside is very fond of asking, is to test your grasp of the foundation.

What’s the difference between GET and POST?

Request parameters: GET Request parameters are passed through a URL, with multiple parameters connected by &; The POST request is placed in the request body. Request caching: GET requests are cached, but POST requests are not unless manually set. Relative security: GET is to pass the parameters through the URL, will be cached by the browser, easy to be obtained by others, post is relatively safe. Limit the length of request parameters: Get passes parameters through the URL. The browser will limit the length of the URL (HTTP does not). Encoding mode: A GET request can only be encoded by the URL, while a POST request supports multiple encoding modes.

What’s the difference between Http1.1 and Http2.0?

(including but not limited to version 1.1 and 2.0 comparison)

http1.1 

  • Persistent links were introduced, meaning TCP is not closed by default and can be reused by multiple requests
  • Introduce a pipelining mechanism, a TCP connection that can send multiple requests simultaneously
  • Added some cached fields
  • New methods: PUT, DELETE, OPTIONS, PATCH
  • Breakpoint continuation is supported through the Rang header field

http2.0

  • The head of compression
  • multiplexing
  • Binary transmission, header information and data body are binary
  • Request priority, which sets the priority of the data frames so that the server can process them first
  • The server pushes the message actively

Some questions asked:

  • What problems do pipes cause and how does http2.0 solve them
  • What is the principle of head compression
  • What the options method does
  • Http2.0 allows the server to actively push messages. How is that different from WebSocket?

Recommend a god three yuan big guy’s article: HTTP soul ask, consolidate your HTTP knowledge system

Let’s talk about HTTP caching

Once you’ve finished the general flow of strong and negotiated caches, the interviewer may use your answers to further explore your understanding of HTTP caches, such as (including but not limited to) :

Is the 200 status code necessarily returned by the server?

No, a strong cache hit will read the resource directly from memory or disk and return a 200 status code. Try the browser’s back and forward keys.

How do the Expires and cache-control max-age directives determine the expiration time, respectively? What are the advantages and disadvantages?

Why does last-Modified have ETag? What problem was solved?

What are the meanings of no-store and no-cache?

I recommend an article that answers these questions: Understanding HTTP caching with a graph

Why is HTTPS safer than HTTP

The interviewer will ask you to explain what HTTPS does, and will not rule out asking you how encryption works. (PS: byte asked by the interviewer)

The main use of symmetric encryption and asymmetric encryption, recommended reading: thoroughly understand HTTPS encryption principle

Talk about three handshakes and four waves

This question was asked less often, and I only came across it once. I recommend an article I wrote earlier: TCP three handshakes, four waves

JS

0.1 + 0.2! = = 0.3? Why is that?

  • Binary conversion: when js is doing the number calculation, the bottom is converted to binary to calculate, 0.1 to binary is infinite loop decimal, 0.2 is also, but JS usesIEEE754 binary floating point arithmetic, only 53 significant digits are retained after the decimal, resulting in loss of accuracy.
  • On the order: The mantissa with small order should be shifted to the right according to the order difference. When the mantissa is shifted, the number may be lost, which will affect the accuracy.

How to solve the accuracy loss problem mentioned above?

  • So the first thing to do is to expand the decimal point to integers, and then when you’re done adding, you divide back. (Inappropriate, because it is still possible to exceed the JS maximum)
  • Use third-party libraries such asMath.js,big.jsEtc.
  • Convert them to strings, and then add the two strings

closure

  • What is the nature of closures? What kind of problems will be caused
  • Is there any other way to generate closures other than to return a function inside a function? (a)
// The function internally delays calls, resulting in closures
function test () {
  let name = 'tom'
  setTimeout(() = > {
    console.log(name)
  }, 2000)
}
test();
Copy the code

Recommended article: static scope chain and “dynamic” closure chain for JavaScript

What is scope? What is a scope chain? What does a function execution context contain?

This points to the

Interviewer: JS this point

The problem of es6

  • The difference between an arrow function and a normal function
  • What is a temporary dead zone and what is a variable lift
  • What is the difference between “for of” and “for in”? How can “for of” traverse an object?
  • Es6 Map and WeakMap difference, WeakMap to solve what problems?
  • Promise which methods are prototype and instance based

Introduction to ES6 tutorial

Prototype + Prototype chain (this is a must ask question)

As long as you can clearly describe how an object finds its value, you can understand most of the problem.

Explain the above picture:

  • prototypeIs a property specific to the function,__proto__Is a property that every object has, andprototypeIt’s an object in itself
  • When we go to geta.nameIf there is none, it starts with the properties of the object itselfa.__proto__On looking for
  • objecta.__proto__It also points to the constructor functiontesttheprototype(prototype), so froma.__protoLook for properties on thetest.prototypeLook for properties, butprototypeThe (prototype) itself is an object, so the above two steps will be repeated until both are foundObjectThe constructor function, andObject.__protoIs a null value. If there is a value in the middle, it is returned, and if there is no value, it is assignedundefined.
  • Such a chain structure is called a prototype chain

Because constructor on the constructor function prototype refers to the constructor function itself, so

a.constructor === test // true
a.__proto__.constructor === test // true
a.__proto__.constructor === test.prototype.constructor// true
Copy the code

Here’s an interview question to test. Say what you printed out and why.

function test () {

}
test.prototype.then = function () {
  console.log('test => then')}Function.prototype.mythen = function () {
  console.log('Function => mythen')
}
test.mythen();
test.then();
Copy the code

eventLoop

The interviewer will ask questions based on your answers, such as:

  • You just said that JS is single threaded. What’s the difference between a thread and a process?
  • A new page is opened in the browser. How many threads are there?
  • Why are microtasks designed to execute first and macro tasks later?

Here’s an article from a Cool guy: This time, get to the bottom of JavaScript execution

Garbage collection mechanism

  • What are the drawbacks of the marker removal method you just mentioned? How to solve it?
  • Are there any disadvantages to the reference counting you just mentioned?
  • What is the garbage collection mechanism in V8?
  • How does V8 address circular references?

Do you really understand garbage collection

Talk about data types. How do you determine an array

To determine an array:

  • Array.isArray(arr); // true
  • arr instanceof Array; // true
  • arr.constructor === Array; // true
  • Object.prototype.toString.call(arr); // “[object Array]”

Ps: Judging by instanceof and constructor may not be accurate as it may be overwritten.

Common design patterns?

  • What is the abstract factory pattern
  • What’s the difference between the publish subscribe pattern and the Observer pattern
  • What design patterns are used in your projects

Recommended article: Front-end Design Patterns to Master

Browser Rendering process

I usually go through the process based on this picture.

Some questions asked by the interviewer:

  • Will the link tag block the rendering of the page? Why?
  • Why is CSS recommended at the top and JS recommended at the bottom?
  • Will js block the rendering of the page? Why?
  • Does CSS block parsing of HTML? Why is that?
  • Does CSS block HTML rendering? Why is that?

Js execution is a separate thread, and rendering is the responsibility of the GUI rendering thread. The two threads are mutually exclusive, so it makes sense that JS will block the rendering of the page.

CSS will not block HTML parsing, parsing HTML and parsing CSS are parallel, but CSS will block HTML rendering, because the page is rendered using style Rules + DOM Tree.

Normally, if you encounter a script tag during page parsing, you will stop HTML parsing (as shown below), download the script, execute the script immediately after the download, and then continue parsing the HTML, so if the script download is slow, you will end up with a blank screen.

Defer: The HTML is parsed and the script is downloaded in parallel (asynchronously), and the script is executed after the HTML is parsed but before DOMContentLoaded is triggered. Async: HTML parsing and script downloading are parallel (asynchronous). Scripts are executed immediately after downloading and HTML parsing is interrupted.

Recommended Reading:

How browsers work: Behind the scenes of the new Web browser,

Browser rendering process and performance optimization in 8 interview questions

Performance optimization

I usually answer from the HTTP request + code level + build tool.

Is there a difference between setTimeout and requestAnimationFrame? Which is better? Why is that?

There’s a difference:

  • accuracy

SetTimeout is not accurate for animation, because it is a macro task, and the delay time set is not equal to the immediate execution after the delay time, because the macro task needs to wait for the synchronization task and microtask to complete before executing, which is easy to lose frames; RequestAnimationFrame is executed before the elements are drawn in each frame, which is more precise.

  • Better performance

When an element is hidden or not visible, setTimeout still performs the animation task in the background; RequestAnimationFrame stops the animation, which means less CPU and less memory consumption.

What about the same origin policy? Do you know those cross-domain methods? What is the principle of CORS cross-domain?

CSS

What about the box model?

What does flex: 1 stand for

Have you ever used flex layouts? What are the properties?

What is BFC, what do you usually use it for, and what problems do you solve?

Do you realize that elements are horizontally or vertically centered? As many ways as possible?

Left fixed + right adaptive layout? What are some options?

Redraw and rearrange?

Recommended articles: Reflow and Repaint

React

Face a circle down, found react asked about the same.

What versions of React have you used? What are the differences?

Talk about front-end routing, what is their implementation principle?

Hash routing: Detects url changes by listening for hashChange events to determine whether to update the page.

History route: listens for popState, pushState, and replaceState to determine whether to update the page. Note, however, that the popState event is not triggered by calling the pushState or replaceState methods, but only when the user clicks the browser’s back and forward buttons, or calls the back, forward, and Go methods using JavaScript. If you want to pushState and replaceState to trigger popState events, you need a custom event.

Can you write a simple redux by hand?

After the interviewer finished, give me pen and paper…… After I finished, the interviewer asked me to go over it for him.

function createStore(reducer) {
  let listeners = [];
  let currentState;
  function getState() {
    return currentState
  }
  function dispatch(action) {
    currentState = reducer(currentState, action);
    listeners.forEach(l= > l());
  }
  function subscribe(fn) {
    listeners.push(fn);
    return function unsubscribe() {
      listeners = listeners.filter(l= > l !== fn);
    }
  }
  return {
    getState,
    dispatch,
    subscribe
  }
}
Copy the code

How does the dispatcher find the reducer correctly in redux?

CombineReducers source

Yeah, redux, it doesn’t find a shuttle, it goes through all the reducers on each dispatch…

How does Redux mount middleware? What is the order of execution?

Core function compose

function compose(middlewears) {
  return middlewears.reduce((a, b) = > (. argu) = >a(b(... argu))) }Copy the code

Execution order: Redux middleware is executed backwards.

Have you used any other state management libraries besides Redux?

No.

The downside of Redux?

React lifecycle?

When is setState synchronous and when is setState asynchronous?

Let’s talk about the event mechanism of React. Why is it designed that way? Is there any change in react17?

Recommended article: a thorough understanding of react event system principle

Design benefits:

  • Smooth out browser differences for better cross-platform
  • Avoid garbage collection. React introduces event pools where event objects are acquired or released, avoiding frequent creation and destruction
  • Facilitate unified event management and transaction mechanism

What is the difference between class components and function components?

Is it possible to write hooks within if judgments? Why not?

It is necessary to ensure that the size and order of the Hooks are the same every time you render them. If they are not consistent, react will not get the correct state and will report an error.

What’s the difference between HOC and hooks?

Hooks implementation principle? Can you do it any other way without a linked list?

Based on the list to achieve, can also be simulated with arrays.

What’s the difference between useEffect and componentDidMount?

Useeffect and useLayouteffect difference

  • useEffectDoes not block browser rendering whileuseLayoutEffectWill block browser rendering.
  • useEffectWill be executed after the browser has rendered,useLayoutEffectIs in theDOMAfter the update is complete, the browser executes before drawing.

Introduce react Dom Diff

What about the Vdom?

Are there any performance optimizations done in React?

According to their own mind melon inside the idea, said several.

Recommended article: React Performance optimization 8 ways to learn about

What’s the difference between react.memo () and react.usememo ()?

Interviewer: What’s the difference between the two?

Go to the official website: React. Memo, React. UseMemo

What’s the difference between useCallback and useMemo?

Also connected to the official website address useCallback

React. Fiber? What causes the lag? How does it work in React. Fiber? After breaking the update, how do I find the location to update next time?

This is probably the most popular way to open React Fiber

Functional programming

Q: Is functional programming highly likely to be asked? (Asked several times)

  • What do you know about functional programming?
  • What libraries take advantage of the idea of functional programming?
  • Is Lodash a true functional programming library?

Simple JavaScript functional programming – introduction

How to prevent ref loss in high order components?

ForwardRef: React. ForwardRef

webpack && node

  • What do you do with node? Have you ever used the Node framework?
  • Some basic NODE API, how to delete files, create files, write files.
  • Which modules of Node have you used?

The difference between processes and threads

Introduce the history of modules

Node_modules problem

Suppose NPM installs module A that depends on version 0.0.1 of C and module B that depends on version 0.0.2 of C. How does node_module ensure that A and B find the corresponding package of version C correctly?

How WebPack packaging works

  • Initialization parameters: read and merge parameters from configuration files and Shell statements to get the final parameters;
  • Start compiling: Initialize the Compiler object with the parameters obtained in the previous step, load all configured plug-ins, and execute the run method of the object to start compiling. Determine entry: Find all entry files based on the entry in the configuration
  • Module compilation: Start from the entry file, call all configured loaders to compile the module, then find out the module that the module depends on, and then recurse this step until all the entry dependent files have been processed by this step;
  • Completion of module compilation: After all modules are translated by Loader in step 4, the final content after each module is translated and the output resources of their dependencies are obtained: The last chance to modify the output is to assemble chunks of modules based on the dependencies between the entries and modules, and then convert each Chunk into a separate file and add it to the output list
  • Output completion: After the output content is determined, the output path and file name are determined according to the configuration, and the file content is written to the file system.

How do you optimize WebPack performance?

Recommended article: With you deep Unlock Webpack Series (optimization)

What is the difference between loader and Plugin?

  • Loader (conversion) : Converts CSS and less files into JS files, identifies different file name extensions, and expands the loader that you are familiar with.
  • Plugin: The idea is to listen to some hooks in the WebPack build process and then do something of your own to enrich WebPack’s functionality.

What is the execution order of the Loader? How to write a Loader? How do I write a plugin? Is there an asynchronous loader?

They are executed from right to left and from bottom to top.

Loader/plugin: loader/plugin: loader/plugin: loader/plugin: Plugin: loader/plugin

Loaders can be synchronous or asynchronous.

What does file-loader return?

A string is returned. See file- Loader source address for details

Webpack has several hashes. What’s the difference between them? What kind of hash do you normally use in a project?

  • Hash: Is the hash value of the entire project, which is calculated based on each compilation. After each compilation, a new hash is generated, that is, modifying any file will cause the hash of all files to change.
  • ContentHash: Parses dependent files based on different Entry files, builds corresponding chunks, and generates corresponding hash values (if the data is from the same chunk, the hash values are the same).
  • ChunkHash: Generates a hash value based on the file content. If the file content is the same, the hash value is the same

What’s new in WebPack5?

Recommended article: flying book team Webpack5 start evaluation

How webPack hot updates work?

Recommended article: Easy to understand the webPack hot update principle

The tree – shaking principle?

Using ES Module to do static analysis, through the analysis of ast syntax tree, maintain a scope for each Module, collect the variables used inside the Module, then analyze the scope, delete the unused modules imported, and finally recursively process the file.

How does Babel handle this when converting an arrow function to a normal function?

Parser => transfrom => generator

How to handle this: Find this in the nearest level of scope, cache this with a unique variable name that, and replace this with that.

Write a topic

Throttling and shaking

Interviewer: Can you write a throttling function by hand? Then passed over the pen and paper……

Function image stabilization

Definition: a function fires only once for n seconds, and if it is fired during that time, it is timed again.

Scenarios: Input real-time search, browser resize, and Scroll

  function debounce (fn, delay) {
    let timer;
    return function (. argu) {
      let that = this;
      if (timer) clearTimeout(timer);
      timer = setTimeout(() = >{ fn.apply(that, argu); }, delay); }}Copy the code

Function of the throttle

Definition: An event is executed only once in n seconds, and if it is fired during that time, it does not respond to the event.

Scenario: The form is repeatedly submitted and scrolls to load

// Use a timestamp
function throttle(fn, delay) {
  let previous = new Date(a);return function (. argu) {
    let nowDate = new Date(a);if (nowDate - previous > delay) {
      fn.apply(this, argu); previous = nowDate; }}; }// Use the timer
function throttle(fn, delay) {
  let timer;
  return function (. argu) {
    let that = this;
    if (timer) return false;
    timer = setTimeout(() = > {
      fn.apply(that, argu);
      timer = null; // Release the timer variable to allow the next function to execute
    }, delay);
  };
}
Copy the code

Write a sort of order that you’re familiar with?

Yeah, also with a pen, and when you’re done, give him the idea. I chose a quick sort

// Select a number as the base point, usually the last number
// Then iterate through the arR to find the set of larger and smaller arrays for the base number
// Recurse this step
function quickSort(arr) {
  if (arr.length < 2) {
    return arr;
  }
  const cur = arr[arr.length - 1];
  let left = [];
  let right = [];
  for (let i = 0; i < arr.length - 1; i++) {
    if (arr[i] >= cur) {
      right.push(arr[i])
    } else {
      left.push(arr[i])
    }
  }
  return [...quickSort(left), cur, ...quickSort(right)];
}
console.log(quickSort([1.3.3.6.2.4.1]));
Copy the code

(bytes) Say the print order

The default is non-strict mode

function Foo() {         
  getName = function () { alert(1); }; 
  return this;
}
Foo.getName = function () { alert(2); };
Foo.prototype.getName = function () { alert(3); };
var getName = function () { alert(4); }; 
function getName() { alert(5); }

// Please write the following output:
Foo.getName();
getName();
Foo().getName();
getName();
new Foo.getName();
new Foo().getName();
Copy the code

Correct output sequence: 2 4 1 1 2 3

  • Foo getName (); There’s nothing to say about that. Output 2

  • GetName (); Look at var and function promotion, function priority is greater than var, so output 4

  • Foo (). The getName (); Foo() returns this, where this points to window, and Foo().getName is equivalent to window.getName. But Foo() internally reassigns getName on the window, so it prints 1

  • GetName (); Ditto, output 1

  • New Foo getName (); New has no list of arguments. Its corresponding priority is 18; Member access operator., which corresponds to a priority of 19. So it’s new (foo.getName)(); The new operator executes the method in the constructor, so the output here is 2.

  • New Foo (). The getName (); New takes the argument list, which corresponds to priority 19, and the member access operator. The priority is the same. Sibling operators that are evaluated in order from left to right. New Foo() initializes Foo(); Foo(); Foo(); Foo(); Foo(); Foo()

Instanceof principle, can you try writing an instanceof function

function myInstanceOf(left, right) {
  if (left === null || typeofleft ! = ='object') return false;
  if (typeofright ! = ='function') throw new Error('right must be function')
  let L = left.__proto__;
  let R = right.prototype;
  while(L ! = =null) {
    if (L === R) return true;
    L = L.__proto__;
  }
  return false;
}

Copy the code

Implement the new keyword

  • Create an empty simple javaScript object, i.e. {}
  • Object that will be created__proto__Pointing to the constructorprototype
  • Modify thethisPoint to the
  • If the constructor does not return a value, the created object is returned.
      function myNew (context, ... argu) {
         let obj = Object.create(null);
         obj.__proto = context.prototype;
         let res = context.apply(obj, argu);
         return typeof res === 'object' ? res : obj;
      }

Copy the code

Addition of large Numbers

let a = "123456789012345678";
let b = "1";

function add(a ,b){
   / /...
}
add(a, b) / / '123456789012345679'
Copy the code

Simulate addition, but use ‘0’ to complete the length. For integers, add 0 forward.

let a = "123456789012345678";
let b = "1";
// 1. Find the maximum length first
// 2. Fill the smaller numbers with 0 forward
function add(a ,b){
  let maxLength = Math.max(a.length, b.length);
  a = a.padStart(maxLength, '0');
  b = b.padStart(maxLength, '0');
  / / 123456789012345678
  / / 000000000000000001
  let res = ' '; // The value returned
  let sum = 0; // The sum of appositives
  let t = 0; // The tenth digit of the sum
  let r = 0; // The units digit of the appositives sum
  for(let i = maxLength - 1; i >= 0; i--) {
    sum = parseInt(a[i]) + parseInt(b[i]) + t;
    t = Math.floor(sum / 10) // Get a ten-digit value
    r = sum % 10; // Get the units digit
    res = r + res;
  }
  return res;
}

console.log(add(a, b)); / / 123456789012345679


Copy the code

(didi) flattens the array

Implement a flat function that takes arR and depth

function flat(arr, depth = 1) {
  return depth > 0 ?
    arr.reduce((pre, cur) = > {
      return pre.concat(Array.isArray(cur) ? flat(cur, depth - 1) : cur);
    }, []) :
    arr.slice();
}
Copy the code

Implement an Event class

class EventEmitter {
  constructor(){}// Listen for events
  on(){}// Triggers the event
  emit(){}// Listen only once, the next emit will not be triggered
  once(){}// Remove events
  off(){}}const events = new EventEmitter();
events.on('hobby'.(. argu) = > {
  console.log('Play games'. argu); })let eat = () = > {
  console.log('eat');
}
events.once('hobby', eat);
events.on('hobby'.(. argu) = > {
  console.log('shopping'. argu); }) events.off('hobby', eat);
events.emit('hobby'.1.2.3);
events.emit('hello'.'susan')
// Play game 1, 2, 3
// Go shopping 1 2 3
Copy the code

The answer:

class EventEmitter {
  constructor() {
    this.events = {}; {eventName: [callback,...] }
  }
  on(eventName, callback) {
    if(!this.events[eventName]) {
      this.events[eventName] = [callback];
    } else {
      this.events[eventName].push(callback); }}emit(eventName, ... argu) {
    if(this.events[eventName]) {
      this.events[eventName].forEach(fn= >fn(... argu)) } }off(eventName, callback) {
    if(this.events[eventName]) {
      this.events[eventName] = this.events[eventName].filter(fn= >callback ! == fn && fn.l ! == callback); }}once(eventName, callback) {
    const _once = () = > {
      callback();
      this.off(eventName, _once)
    }
    _once.l = callback;
    this.on(eventName, _once)
  }
}
Copy the code

Implement the thousandth format function

   // Receive a number and return a string
   function format(number) {}console.log(format(12345.7890)); // 12,345.789,0
  console.log(format(0.12345678));/ / 0.123, 456,78
  console.log(format(123456)); // 123,456
Copy the code

Train of thought

  • Based on the decimal point segmentation, for the integer part, go back to front, add by 3.
  • The decimal point is convenient from the front to the back, separated by three.
  function format (number) {
     let str = number.toString();
     let [int, dec = ' '] = str.split('. ');
     let intStr = ' '
     for (let i = int.length - 1; i >= 0; i--) {
        if ((int.length - i) % 3= = =0&& i ! = =0) {
             intStr = ', ' + int[i] + intStr;
        } else{ intStr = int[i] + intStr; }}let decStr = ' ';
    if (dec.length > 0) {
       for (let i = 0; i < dec.length; i ++) {
          let sum = decStr + dec[i];
          if ((i + 1) %3= = =0) {
             decStr = sum + ', ';
          } else{ decStr = sum; }}}return decStr.length > 0 ? `${intStr}.${decStr}` : `${intStr}`;
};

Copy the code

Return a random name based on the weight information passed in. (Random probability based on weight)

The first time I didn’t understand the question, the interviewer explained.

/ * * *@description: Returns a random name based on the weight information passed in (the random probability is based on the weight) *@param {Array} personValue
 * @returns {String} PersonName name * /
var getPersonName = function (personValue) {}const person = [
  {
    name: 'Joe'.weight: 1
  },
  {
    name: 'bill'.weight: 10
  },
  {
    name: 'Cathy'.weight: 100}]function getResult(count){
  const res = {}
  for(let i = 0; i < count; i++){
    const name = getPersonName(person)
    res[name] = res[name] ? res[name] + 1 : 1
  }

  console.log(res) 
}
getResult(10000)

Copy the code

The answer:

var getPersonName = function (personValue) {
  // Mark the interval and get the total weight
  let sum = personValue.reduce((pre, cur) = > {
    cur.startW = pre;
    return cur.endW = cur.weight + pre
  }, 0);
  let s = Math.random() * sum; // Get a random number between 0 and 111
  // Determine the interval of the random number
  let person = personValue.find(item= > item.startW < s && s <= item.endW);
  return person.name;
}

Copy the code

(bytes) implement a promise.all


Promise.all = function (promises) {
  let result = [];
  let count = 0;
  return new Promise((resolve, reject) = > {
    promises.forEach((p, index) = > {
      // Compatibility is not the case for a promise
      Promise.resolve(p).then((res) = > {
        result[index] = res;
        count++;
        if(count === promises.length) {
          resolve(result)
        }
      }).catch((err) = >{ reject(err); })})}); }Copy the code

The sum of two numbers

The interviewer asked you if you could optimize the sum of two numbers to O(n^2). And then you have this down here.

var twoSum = function(nums, target) {
  let len = nums.length;
  let map = new Map(a);for(let i = 0; i < len; i++) {
      if (map.has(target - nums[i])) {
          return [map.get(target - nums[i]), i]
      } else {
          map.set(nums[i], i)
      }
  }
};

console.log(twoSum([2.7.11.15].9))
Copy the code

(bytes) No duplicate oldest string

Force buckle original question: no repeat most eldest son string

var lengthOfLongestSubstring = function(s) {
  let arr = [];
  let max = 0;
  for (let i = 0; i < s.length; i++) {
    let index = arr.indexOf(s[i])
    if(index ! = = -1) {
      arr.splice(0, index + 1);
    }
    arr.push(s.charAt(i));
    max = Math.max(arr.length, max);
  }
  return max;
};
Copy the code

Implement the new Queue class

new Queue()
.task(1000.() = >console.log(1))
.task(2000.() = >console.log(2))
.task(3000.() = >console.log(3)).start(); Implement a Queue function, after calling start, 1 second after printing1, and then 2s after printing2, and then print after 3s3
Copy the code

The answer:

function sleep(delay, callback) {
  return new Promise((resolve, reject) = > {
    setTimeout(() = >{ callback(); resolve() }, delay); })}class Queue {
  constructor() {
    this.listenser = [];
  }
  task(delay, callback) {
    // Collect the function
    this.listenser.push(() = > sleep(delay, callback));
    return this;
  }
  async start() {
    // Iterate over the function
    for (let l of this.listenser) {
      await l()
    }
  }
}

new Queue()
.task(1000.() = >console.log(1))
.task(2000.() = >console.log(2))
.task(3000.() = >console.log(3)).start();

Copy the code

conclusion

There are also a lot of scene questions, asking you to give solutions, the middle experience is too long, the interview record is not good enough, many questions have forgotten. The first interview is basically about the basics, and the next few rounds will delve deeper into the project and ask you for solutions. In this interview, I also found my shortcomings. I didn’t think enough in the process of code writing. I hope I can think more in the future.