Remember the interview process once manufacturers

Foreword

In mid-June 2019, nothing exciting really tired before work and humble salary, despite opposition from their loved ones, resolutely decided to go alone to the coastal cities, thinking to find a job more challenging to thoroughly bottom to re-polish themselves, but to pursue a better salary. Prior to this course, he will use his spare time after work every day to swot consolidate brush problem and so, probably from the beginning of March, it lasted more than three months. Then from mid-June until the end of June interview, about the middle of two weeks, in fact, my education and background is not outstanding, but my personal feeling is probably because they do resume slightly okay (I might back out of a separate article to talk about me a little bit of experience on a resume), manufacturers can make HR more Kanji Yan, through the middle plane of companies, including the Himalayas, Ctrip, beep beep miles miles, fluent, dragonfly FM, love recycling , after another 4,5 Offer to get it, now positive, so here part of the record before the interview questions , and share exchange.

text

1. Lie Bear Network

The company in fact, I did not understand much about before, is my former colleague recommended that the inside of the salary is good, then I was also have free time, so go try, though the company did not mention the above known large companies, but his face questions I think it is quite component.

1.1 Please state the following code execution order

async function async1() {
  console.log(1);
  const result = await async2();
  console.log(3);
}

async function async2() {
  console.log(2);
}

Promise.resolve().then(() => {
  console.log(4);
});

setTimeout(() => {
  console.log(5);
});

async1();
console.log(6);

1.2 done manually Promise, write pseudocode

Fortunately, just before the interview access to the information under this part of the process so the answer is fairly handy, mainly to follow Promise / A + specification:

(1) a promise must have three states (pending | fulfilled (resolved) | rejected), when in a pending state, can be transferred to the fulfilled (resolved) or a rejected state condition is fulfilled (resolved) or a rejected state state, no state variable;

(2) The method then must have a promise, then the method must accept two parameters:

// onFulfilled在状态由pending -> fulfilled(resolved) 时执行,参数为resolve()中传递的值
// onRejected在状态由pending -> rejected 时执行,参数为reject()中传递的值
promise.then(onFulfilled,onRejected)

(3) then you must return a promise:

promise2 = promise1.then(onFulfilled, onRejected);

Come posted implement code directly:

Reference from: to achieve a perfect line with Promise / A + Specification Promise

function myPromise(constructor){
    let self=this;
    self.status="pending" //定义状态改变前的初始状态
    self.value=undefined;//定义状态为resolved的时候的状态
    self.reason=undefined;//定义状态为rejected的时候的状态
    self.onFullfilledArray=[];
    self.onRejectedArray=[];
    function resolve(value){
       if(self.status==="pending"){
          self.value=value;
          self.status="resolved";
          self.onFullfilledArray.forEach(function(f){
                f(self.value);
                //如果状态从pending变为resolved,
                //那么就遍历执行里面的异步方法
          });
        
       }
    }
    function reject(reason){
       if(self.status==="pending"){
          self.reason=reason;
          self.status="rejected";
          self.onRejectedArray.forEach(function(f){
              f(self.reason);
             //如果状态从pending变为rejected, 
             //那么就遍历执行里面的异步方法
          })
       }
    }
    //捕获构造异常
    try{
       constructor(resolve,reject);
    }catch(e){
       reject(e);
    }
}

myPromise.prototype.then=function(onFullfilled,onRejected){
    let self=this;
    let promise2;
    switch(self.status){
      case "pending":
        promise2 = new myPromise(function(resolve,reject){
             self.onFullfilledArray.push(function(){
                setTimeout(function(){
                  try{
                     let temple=onFullfilled(self.value);
                     resolvePromise(temple)
                    }catch(e){
                       reject(e) //error catch
                    }
                })
             });
             self.onRejectedArray.push(function(){
                setTimeout(function(){
                   try{
                       let temple=onRejected(self.reason);
                       resolvePromise(temple)
                     }catch(e){
                       reject(e)// error catch
                   }
                })
             });
        })
      case "resolved":
        promise2=new myPromise(function(resolve,reject){
           setTimeout(function(){
               try{
                  let temple=onFullfilled(self.value);
                  //将上次一then里面的方法传递进下一个Promise状态
                  resolvePromise(temple);
                }catch(e){
                  reject(e);//error catch
               }
           })
        })
        break;
      case "rejected":
        promise2=new myPromise(function(resolve,reject){
           setTimeout(function(){
             try{
               let temple=onRejected(self.reason);
               //将then里面的方法传递到下一个Promise的状态里
               resolvePromise(temple);   
             }catch(e){
               reject(e);
             }
           })
        })
        break;
      default:       
   }
   return promise2;
}

function resolvePromise(promise,x,resolve,reject){
  if(promise===x){
     throw new TypeError("type error")
  }
  let isUsed;
  if(x!==null&&(typeof x==="object"||typeof x==="function")){
      try{
        let then=x.then;
        if(typeof then==="function"){
           //是一个promise的情况
           then.call(x,function(y){
              if(isUsed)return;
              isUsed=true;
              resolvePromise(promise,y,resolve,reject);
           },function(e){
              if(isUsed)return;
              isUsed=true;
              reject(e);
           })
        }else{
           //仅仅是一个函数或者是对象
           resolve(x)
        }
      }catch(e){
         if(isUsed)return;
         isUsed=true;
         reject(e);
      }
  }else{
    //返回的基本类型,直接resolve
    resolve(x)
  }
}

1.3 Please state the following print results

let a = {a: 10};
let b = {b: 10};
let obj = {
  a: 10
};
obj[b] = 20;
console.log(obj[a]);

My answer is: 20. This question is the main test for JS data types as well as proficiency in ES6 property name expression to understand. On the question of obj[b] = 20the assignment, objin fact, has become {a: 10, [object Object]: 20}, it is as if the expression is an object attribute name, then by default objects are automatically converted to a string [object Object], the last step to obtain obj[a]the time, a itself is a objects, it will be converted to obtain obj[object Object]is the 20-step assignment.

1.4 arrays to say a few heavy way

This fact, the Internet has a lot a lot of implementation, I will probably give the following:

let originalArray = [1,2,3,4,5,3,2,4,1];

// 方式1
const result = Array.from(new Set(originalArray));
console.log(result); // -> [1, 2, 3, 4, 5]

// 方式2
const result = [];
const map = new Map();
for (let v of originalArray) {
    if (!map.has(v)) {
        map.set(v, true);
        result.push(v);
    }
}
console.log(result); // -> [1, 2, 3, 4, 5]

// 方式3
const result = [];
for (let v of originalArray) {
    if (!result.includes(v)) {
        result.push(v);
    }
}
console.log(result); // -> [1, 2, 3, 4, 5]

// 方式4
for (let i = 0; i < originalArray.length; i++) {
    for (let j = i + 1; j < originalArray.length; j++) {
        if (originalArray[i] === originalArray[j]) {
            originalArray.splice(j, 1);
            j--;
        }
    }
}
console.log(originalArray); // -> [1, 2, 3, 4, 5]

// 方式5
const obj = {};
const result = originalArray.filter(item => obj.hasOwnProperty(typeof item + item) ? false : (obj[typeof item + item] = true));
console.log(result); // -> [1, 2, 3, 4, 5]

1.5 How to re-array of objects?

The subject not only to the company and asked, beginning to force a look ignorant, thinking of the memory address of each object itself is not the same, what significance to heavy, heavy, non-go, it would only pass JSON.stringifyserialized into a String way to compare (this method has some drawbacks) after or recursive were key - value comparison, but for large nested objects, it is quite time-consuming, so it is no good answer, then the interviewer told me that according to on a specific property of each object to be heavy, because there may be duplicate id consideration of the data returned from the server, it is necessary to filter distal end, as follows:

const responseList = [
  { id: 1, a: 1 },
  { id: 2, a: 2 },
  { id: 3, a: 3 },
  { id: 1, a: 4 },
];
const result = responseList.reduce((acc, cur) => {
    const ids = acc.map(item => item.id);
    return ids.includes(cur.id) ? acc : [...acc, cur];
}, []);
console.log(result); // -> [ { id: 1, a: 1}, {id: 2, a: 2}, {id: 3, a: 3} ]

2. Ctrip

Was carried out a day before the electricity side, then the next day on-site surface, two take turns to ask the interviewer, lasted about a half hour of it, ask questions, or more, some of the problems a long time or do not remember , forgive me!

2.1 understand the deep and shallow copy copy it?

Shallow copy means to create an object that has an exact copy of the original object's property value. If the property is a primitive type, then the copy is the value of the basic type, if the property is a reference type, then the copy is the memory address, so if one of the objects to modify some of the properties, then the other objects will be affected.
Deep copy is from the memory out a full copy of an object and the heap memory allocated for a new memory area to store and modify the properties of the object will not affect the original object.

2.2 deep copy and shallow copy implementations are what?

Shallow copy: (1) Object.assign manner (2) slice through the object by an array of methods (4) concat method extended operator array (3).
Deep copy: (1) by JSON.stringify to serialize objects (2) achieved manually in a recursive manner.

2.3 is probably referring to the next seamlessly carousel ideas?

The idea at first simply to achieve carousel, multiple pictures in order from left to right, the left and right click button to toggle the picture when, left of the picture so that the offset value of the parent container to increase or decrease the size of the width of a single image while a transition with CSS3 transition or a handwriting animation function, which can achieve a relatively smooth animation. For seamless carousel, I was thinking is another copy of a parent container out of the picture, for example, it had a <ul><li></li><li></li></ul>correspondence two pictures, now becomes two ulcorresponding to 4 pictures while ulthe parent container monitor itself scrollLeft, if the value has than or equal to a ulwidth of the immediately its scrollLeftvalue is reset to 0, so that they can rotate from the starting point, seamless effect.

2.3 say the results of each code

  var a = 10;
  var obj = {
      a: 20,
      say: function () {
          console.log(this.a);
      }
  };
  obj.say();

This is a simplified version of my being, I do not remember a specific topic, anyway, it is to test the point of this question, the answer to the question 20. Then the interviewer continue to ask, how to print out 10, given as follows:

  // 方式1
  var a = 10;
  var obj = {
      a: 20,
      say: () => {  // 此处改为箭头函数
          console.log(this.a);
      }
  };
  obj.say(); // -> 10
  
  // 方式2
  var a = 10;
  var obj = {
      a: 20,
      say: function () {
          console.log(this.a);
      }
  };
  obj.say.call(this); // 此处显示绑定this为全局window对象
  
  // 方式3
  var a = 10;
  var obj = {
      a: 20,
      say: function () {
          console.log(this.a);
      }
  };
  
  var say = obj.say; // 此处先创建一个临时变量存放函数定义,然后单独调用
  say();

2.4 Vue life cycle What?

创建:beforeCreate,created;
载入:beforeMount,mounted;
更新:beforeUpdate,updated;
销毁:beforeDestroy,destroyed;

2.5 How to design a mobile terminal friendlier Header components?

At that time the idea of ​​the head (Header) is generally divided into left, center, and right parts, divided into three regions to design, among the main title, the title of each page is certainly different, it can be done by way of vue props may be configured to be exposed to the outside, most of the left side of the page back button are possible, but different styles and content, are generally functional right operation buttons, it can be left and right sides of the slot by vue slot way to achieve diversification of foreign exposure, but can also provide default slot slot to unify the default page style.

2.6 tell the difference between space-between and space-around in?

The layout of the flex content is, in fact, a difference margins, a horizontal layout, the space-betweenright and left sides without margins, while the space-aroundleft and right sides of leave margins, vertical layout Similarly, as shown below:

2.7 You know front-end performance optimization

In fact, this scheme, or more, from the DOM level , CSS style level and JS logic levels respectively to start, probably given the following:

(1) reduce the number of access to the DOM, the DOM may be cached variable;

(2) reducing redraw and reflux , any condition which would redraw and reflux operations should be performed to reduce, may be multiple operations into one ;

(3) maximize the use of the event delegate methods for event bindings, to avoid a large number of bindings lead to excessive memory footprint;

(4) css level as possible flat , to avoid excessive levels of nesting, to make use of specific selectors to distinguish;

(5) to make use of animation CSS3 animation properties achieved, GPU hardware acceleration opening;

(6) Picture in advance before loading the specified width and height or from the document flow , to avoid reflux recalculated after page loading due;

(7) css file <head>label incorporated, js file <body>label introduced to optimize critical rendering path ;

(8) to accelerate or reduce HTTP requests, using a CDN to load static resources , rational use of browser strong caching and consultation caching , small picture, you can use Base64 instead, the rational use of browser prefetch instruction prefetch and preload instruction PRELOAD ;

(9) compressing obfuscated code , remove dead code , the code resolution to reduce the file size;

(10) smaller pictures FIG sprite , select the appropriate image quality , size and form , to avoid the waste flow.

2.8 git people how to resolve conflicts when cooperation

The main conflict is seen in people when modifying the same part of the same file, when the other party before you push, and then you later pushwhen the git detected twice submission does not match suggesting you Conflict, then you are pulldown in the code of conflict local use =====separated, then you need to find the corresponding code for developers to discuss the trade-offs, cut can not be free to modify and forced to submit , post-conflict again pushcan be.

3. Himalayas

It was two technicals, on one side, an on-site surface, electricity face some very vague answer or topic, site surface feel can also be right.

Implement a manual bind 3.1

code show as below:

Function.prototype.bind = function(context, ...args1) {
    if (typeof this !== 'function') {
        throw new Error('not a function');
    }
    
    let fn = this;
    let resFn = function(...args2) {
        return fn.apply(this instanceof resFn ? this : context, args1.concat(args2));
    };
    const DumpFunction = function DumpFunction() {};
    DumpFunction.prototype = this.prototype;
    resFn.prototype = new DumpFunction();
    
    return resFn;
}

3.2 talk of understanding React Hooks

In React, we generally have two ways to create a component, the class definition or function definition ; in the class definition, we can use many of the features React, such as state or various lifecycle hook, but it can not be used in the function definition. So React 16.8 introduced a new version React Hooks functions, we can use the characteristics of the class definition in order to use them in the function definition by React Hooks. React Hooks course itself appears to reuse components, as well as life-cycle as compared to the hooks among the class definition, React Hooks are provided useEffecta plurality of hooks life cycle are combined, so that the dispersion in the original class definition logic becomes more centralized, easy maintenance and management.

3.3 React Hooks how to distinguish among useEffect lifecycle hook

useEffectIt can be seen componentDidMount, componentDidUpdateand the componentWillUnmountcombination of the three. useEffect(callback, [source])Receiving two arguments, it is called as follows:

 useEffect(() => {
   console.log('mounted');
   
   return () => {
       console.log('willUnmount');
   }
 }, [source]);

It calls the lifecycle methods mainly by the second argument [source]to be controlled, the following situations:

(1) [source]When the parameter is not passed, then every time a priority call that function last saved function returned, and then call the external function;

(2) [source]the parameters passed [], then external function is only called once during initialization, the function returns the final will only be called once when the component unloading;

(3) [source]When the parameter has a value, it will only listen to that function after a change in values in the array of priority return call, and then call an external function.

3.4 What is a high-order component (HOC)

High-order component (Higher Order Componennt) is actually not the component itself, but a function that receives a meta element as a parameter, and then returns a new enhancements , high order components appear to logic itself is multiplexed, for example :

  function withLoginAuth(WrappedComponent) {
      return class extends React.Component {
          
          constructor(props) {
              super(props);
              this.state = {
                isLogin: false
              };
          }
          
          async componentDidMount() {
              const isLogin = await getLoginStatus();
              this.setState({ isLogin });
          }
          
          render() {
            if (this.state.isLogin) {
                return <WrappedComponent {...this.props} />;
            }
            
            return (<div>您还未登录...</div>);
          }
      }
  }

3.5 say the results of each code

parseInt('2017-07-01') // -> 2017
parseInt('2017abcdef') // -> 2017
parseInt('abcdef2017') // -> NaN

3.6 React implemented mobile applications, if Caton appear, which can be considered optimization

(1) increase the shouldComponentUpdatehook of the old and the new propsare compared, if the value of the same update is blocked, to avoid unnecessary rendering, or to use PureReactComponentan alternative Component, inside the package has a shouldComponentUpdateshallow comparison logic;

(2) For the same configuration tables or other nodes, each of which increases as the unique keyattributes to facilitate React the diffalgorithm selected for that node, the node to reduce the creation and deletion operations;

(3) renderfunction in reducing similar onClick={() => {doSomething()}}wording, each call renderwill create a new function when the function, even if there is no change in the content, can lead to unnecessary re-rendering nodes, it is recommended to save the members of the object function in assembly , this will only create one;

(4) components propsif need to go through a series of operations in order to get the final result, you might consider using reselectthe library to cache results, if the propschange in value has not occurred, the result took directly from the cache, avoiding the high cost of operation;

(5) webpack-bundle-analyzeranalysis of the current page dependencies, whether there is unreasonable, if there is, find the optimum point and optimized.

3.7 (algorithm title) How to find the largest number from the number 10 10000

He did not answer questions well, two words to describe: pulpy! It is a problem encountered algorithm nervous Mongolia circle, a positive solution to it.

Create a minimum stack structure, initial value 10 before number of 10,000, the number 10 in the top of the stack is the minimum number. Then traverse the rest of the number 9990, if the number is less than the number of the top of the stack, will be discarded or remove the top of the stack number, the number of traversed inserted stack, the stack structure is automatically adjusted, it is possible to ensure that the number of top of the stack 10 must be the smallest number. After traversing is completed, the number 10 is the biggest pile of these 10,000 the number 10 inside.

4. fluent

There was an electric surface in advance, and then a few days before going to the scene face, scene two technical side, the company is focusing on the underlying principle, the answer was not very good.

4.1 React to achieve a stabilization of fuzzy query input box

code show as below:

  // 防抖函数
  function debounce(fn, wait, immediate) {
    let timer = null;
    
    return function (...args) {
        let context = this;
        
        if (immediate && !timer) {
            fn.apply(context, args);
        }
        
        if (timer) clearTimeout(timer);
        timer = setTimeout(() => {
            fn.apply(context, args);
        }, wait);
    }
  }
  
  class SearchInput extends React.Component {
  
      constructor(props) {
          super(props);
          this.state = {
              value: ''
          };
          this.handleChange = this.handleChange.bind(this);
          this.callAjax = debounce(this.callAjax, 500, true);
      }
      
      handleChange(e) {
          this.setState({
              value: e.target.value
          });
          this.callAjax();
      }
      
      callAjax() {
          // 此处根据输入值调用服务端接口
          console.log(this.state.value);
      }
      
      render() {
          return (<input type="text" value={this.state.value} onChange={this.handleChange} />);
      }
      
  }

4.2 a manual request function package, can set the maximum number of requests, the request is not successful request, the request fails until it exceeds the maximum number of continuation request

code show as below:

  function request(url, body, successCallback, errorCallback, maxCount = 3) {
      return fetch(url, body)
               .then(response => successCallback(response)
               .catch(err => {
                   if (maxCount <= 0) return errorCallback('请求超时');
                   return request(url, body, successCallback, errorCallback, --maxCount);
               });
  }
  
  // 调用
  request('https://some/path', { method: 'GET', headers: {} }, (response) => {
      console.log(response.json());
  }, (err) => console.error(err));

4.3 JS difference in the == and ===

==Represents equal abstract , different types of value when both sides will do first implicit type conversion , and then to compare values;
===represents a strictly equal , will not do the type conversion of different types on both sides must not equal.

The difference between 4.4 GET and POST

(1) GET request rollback and refresh the browser is harmless, and POST requests will inform the user data would be resubmitted;

(2) GET request may be bookmarked, POST request can not be bookmarked;

(3) GET request can be cached, POST request is not cached;

(4) GET request can only be url encoded, and the POST request support multiple encoding.

(5) GET request parameters can be retained in the browser's history, POST requests are not retained;

(6) GET request length is limited, when transmitting data, the GET request to add data to the URL, URL length is limited, the maximum length of 2048 characters, POST request no length limit;

(7) GET request to allow only ASCII characters, POST request unlimited, support for binary data;

(8) GET request security is poor, data is exposed in the URL of the browser can not be used to transmit sensitive information, better security POST request, the data is not exposed to the URL;

(9) GET request idempotent (multiple requests will not impact on resources), POST requests are not idempotent;

(10) GET request will generate a TCP packet, the POST request will have two TCP data packets, as GET request http header and data will be sent together with the data, while POST request will first send http header data, the server response 100 (continue), then the POST request http data resending data, then the server 200 returns the response data.

Said cache mechanism under 4.5 browser

Browser caching mechanism can be divided into strong caching and consultation cache , the server may increase in response header Cache-Control / Expires to set the current resource cache lifetime (for the Cache-Control max-age of a higher priority than the Expires ), when the browser sends a request again, will first determine whether the cache expires, if it has not expired cache hit strong, direct use of the browser's local cache resources, if it has expired using the negotiated cache, the cache negotiation generally have the following two options:

(1) a unique identifier: an Etag (server response carries) & If-None-Match (client request carries) ;

(2) Last Modified: Last-Modified (server response carries) & If-Modified-Since (client request carries), a lower priority than an Etag .
Whether the server judgment value consistent, if consistent, then directly back 304 tells the browser to use the local cache, if not a new resource is returned.

5. Bilibili

Scene two technical side, asked a lot of test of basic knowledge of the subject, on the whole answer fairly satisfied with it.

In transition and animation properties 5.1 CSS3 are what

transition Transition animation:

(1) transition-property: Property Name

(2) transition-duration: time interval

(3) transition-timing-function: animation curve

(4) transition-delay: Delay

animation Keyframe animation:

(1) animation-name: Animation name

(2) animation-duration: time interval

(3) animation-timing-function: animation curve

(4) animation-delay: Delay

(5) animation-iteration-count: Animations

(6) animation-direction: direction

(7) animation-fill-mode: prohibition mode

5.2 box model

It means that when rendering a page, the layout model used DOM element, a space occupied element consists of several components, the content (Content), padding (padding), the border (border) and margins (margin) . It can box-sizingbe set, wherein the content IE box model contains padding and border, which is where the cassette different from the W3C standard model.

5.3 selector priority

! Important> inline style> id selector> class selector> tag selector> *> inherited> Default

The difference between 5.4 forEach, map and filter the

forEachThrough the array, the parameter is a callback function, the callback function takes three parameters, the current element, the element index, the entire array;
mapand forEachthe like, through the array, but its return value of the callback function will form a new index structure array, and the new array consistent with the original array, the original array unchanged;
filterreturns a subset of the original array, logic for determining the callback function returns truethen the current array elements to return to, or exclude the current element, the original array unchanged.

5.5 implement a function currying

code show as below:

const curry = (fn, ...args1) => (...args2) => (
 arg => arg.length === fn.length ? fn(...arg) : curry(fn, ...arg)
)([...args1, ...args2]);

// 调用
const foo = (a, b, c) => a * b * c;
curry(foo)(2, 3, 4); // -> 24
curry(foo, 2)(3, 4); // -> 24
curry(foo, 2, 3)(4); // -> 24
curry(foo, 2, 3, 4)(); // -> 24

5.6 Cross-tab of communication which

(1) BroadCast Channel

(2) Service Worker

(3) LocalStorage + window.onstorage监听

(4) Shared Worker + polling timer (the setInterval)

(5) IndexedDB + polling timer (the setInterval)

(6) cookie + timer polling (setInterval)

(7) window.open + window.postMessage

(8) Websocket

5.7 implement a data type determination function

code show as below:

function getType(obj) {
   if (obj === null) return String(obj);
   return typeof obj === 'object' 
   ? Object.prototype.toString.call(obj).replace('[object ', '').replace(']', '').toLowerCase()
   : typeof obj;
}

// 调用
getType(null); // -> null
getType(undefined); // -> undefined
getType({}); // -> object
getType([]); // -> array
getType(123); // -> number
getType(true); // -> boolean
getType('123'); // -> string
getType(/123/); // -> regexp
getType(new Date()); // -> date

to sum up

Some interview questions really can not remember, in fact, most of the above title is quite basic, asked the frequency is relatively high, there just do a simple share, we want to help a little more or less, and also hope to we can talk about, if there is doubt welcome message discussed.

communicate with

The article has been updated to synchronize Github blog , if the article can still feel, feel free to star!

One of your thumbs, so I deserve more effort!

The face of adversity to grow, and only continue to learn in order to become better themselves, and the king of mutual encouragement!

Guess you like

Origin www.cnblogs.com/xyy2019/p/11787817.html