【Interview】Intermediate front-end interview question record and answer summary

foreword

I recently interviewed an intermediate front-end development engineer of an Internet company. Good guy, come up and start handwriting questions, algorithm tests and so on.

Hereby record the exam questions. See if it can help everyone, some questions are forgotten, let's record it roughly.

Table of contents

--Handwriting questions--

1. The difference between let and var

2. Event loop execution result

3. Algorithm questions

4. Promise inspection

5. Algorithm questions, judging valid parentheses

--Technical questions--

6. Talk about the diff algorithm

7. The process of entering the url to the page display

9. The working process of webpack, and what things have been used in webpack

at last


1. The difference between let and var

for(let i = 0; i<5; i++) {

setTimeout(() => console.log(i),0)

}

Ask about the execution result, and the execution result of changing let to var

My answer:

At that time, I saw that it relied on let block-level scope. I usually like to use let in for loops, so I basically got the answer right, but I entered the wrong number of loops, speechless. . .

correct answer:

let: 0 1 2 3 4

was: 5 5 5 5 5

Parse:

var declares a global variable, and then setTimeout is an asynchronous function. After the loop is completed, i becomes 5, so five 5s are output;

And let is block-level, each cycle has its own local scope, so output 0-4

2. Event loop execution result

I can't remember the title clearly, it is probably the following two, I probably wrote it

setTimeout(function() {
  console.log('1')
  new Promise(function() {
      console.log('2')
  }).then(
    console.log('3')
  )
},0)


new Promise(function() {
  console.log('4')
}).then(
  console.log('5')
)

setTimeout(function() {
  new Promise(function() {
      console.log('6')
  }).then(
    console.log('7')
  )
},0)

correct answer:

script start  2  3 script end  1   4

setTimeout(function() {
  console.log('1')
  new Promise(function() {
      console.log('2')
  }).then(
    console.log('3')
  )
},0)


new Promise(function() {
  console.log('4')
}).then(
  console.log('5')
)

setTimeout(function() {
  new Promise(function() {
      console.log('6')
  })
},0)

correct answer:

4  5  1  2  3  6  

My answer:

The first answer was very smooth, and then the second one got stuck. I was a little confused at the time. The result of the first writing was to execute all the macro tasks and then go to the micro task queue. Later, I realized that it was to execute a macro task, and then execute all micro tasks.

So at that time, I was stuck on whether it was 1263 or 1236 at the end. Fortunately, it was finally corrected.

3. Algorithm questions

There is a function add:

Execute add(1)(1+2+3+4) , the result is 11

Execute add(2)(1+2+3+4) , the result is 12

Execute add(2)(1+2+3+4+1+1) , the result is 14

Please write the add function

My answer:

First of all, let me observe the characteristics of this function.

After observing for a while, it is found that the value entered for the second time is added to the value entered for the first time

Then, the function can be executed continuously, and it is certain that the add function must return a method

So my answer:

Write it out for the first time:

function add(num) {
  let result 
  return function(num,...rest){
    let result = rest.reduce((a,b) => a+b)+n
    return result
  }
}

For the first answer, I follow my thinking, add the latter value to the previous value, so the latter value is received with the remaining parameter of ...rest, because the number of parameters passed in the second time is not necessarily the same, but the interviewer reminded that the second call did not pass num. That's why I realized that the second time I just passed the value of the second time.

Then I immediately thought of replacing the rest parameter with arguments, and then, the first number passed in is declared in the first-level function, which constitutes a closure, and the second-level function can be used directly~ Nice

function add(num) {
  let n = num
  return function(){
    let arr = Array.from(arguments)
    let result = arr.reduce((a,b) => a+b)+n
    return result
  }
}

4. Promise inspection

var a = Promise.resolve()
var b = Promise.resolve('foo')
var c = Promise.resolve(() => null)
var d = Promise.resolve(() => undefined)
var e = Promise.resolve(() => 'foo')
var f = Promise.resolve(() => Promise.resolve('foo'))
var g = Promise.resolve(() => Promise.reject('err'))
var h = Promise.resolve(() => new Promise(() => {
  Error('err')
}))
console.log(a,b,c,d,e,f,g,h)

Please write the values ​​of a, b, c, d, e, f, g, h

My answer:

When I saw this question, I was stupefied and talked nonsense, half of the answers were wrong.

Correct answer:
Promise {<fulfilled>: undefined}

Promise {<fulfilled>: 'foo'}

Promise {<fulfilled>: f}

Promise {<fulfilled>: f}

Promise {<fulfilled>: f}

Promise {<fulfilled>: f}

Promise {<fulfilled>: f}

Parse:

MDN Detailed Explanation

Promise.resolve()method returns a  Promise object that resolves with the given value. If the value is a promise, that promise is returned; if the value is a thenable (ie has a  "then" method ), the returned promise will "follow" that thenable, taking its final state; otherwise the returned promise will be fulfilled with the value. This function flattens nested layers of promise-like objects (eg, promises that resolve to something) into a single layer.

Sometimes it is necessary to convert an existing object into a promise object, and the Promise.resolve() method does this.

Promise.resolve('foo')

Equivalent to

new Promise(resolve => resolve('foo'))

Promise.resolve() has four parameters

The first type: without any parameters

setTimeout(function () {
  console.log('three');
}, 0);

Promise.resolve().then(function () {
  console.log('two');
});

console.log('one');
// one two three

Equivalent to a promise object in resolve state

The second type: ordinary variables or ordinary objects

const p = Promise.resolve('Hello');

p.then(function (s){
  console.log(s)
});
// Hello

Equivalent to the promise object of the resolve state

The third: the parameter is a Promise instance

If the argument is a Promise instance, then Promise.resolve will return the instance without any modification.

The fourth type: the parameter is a thenable object

//thenable对象指的是具有then方法的对象,比如下面这个对象

let thenable = {
  then: function(resolve, reject) {
    resolve(42);
  }
};
//Promise.resolve方法会将这个对象转为 Promise 对象,然后就立即执行thenable对象的then方法。

let thenable = {
  then: function(resolve, reject) {
    resolve(42);
  }
};

let p1 = Promise.resolve(thenable);
p1.then(function(value) {
  console.log(value);  // 42
});
//thenable对象的then方法执行后,对象p1的状态就变为resolved,
//从而立即执行最后那个then方法指定的回调函数,输出 42

5. Algorithm questions, judging valid parentheses

Write a method, enter a string with only parentheses, (){}[] [(),{}] {[()]} these will return true

([)] (}) This will return false

My answer:

When I saw this question, I thought to myself: Good guy, I’ve brushed it on Likou, and it’s stable! Thinking about it again, I forgot how to do it. . . Zhuo!

First answer:

My idea is to first judge whether it is an empty string or an even number, and exclude special cases.

Then traverse the string and make judgments on the six conditions of the element ( , ), { , } , [ , ] respectively. For example, if it is a left parenthesis, its right side must be a right parenthesis.

but! The interviewer suggested that only (){}[] can be judged, so what about {[()]}?

Second answer:

I thought of another solution backhand, double pointers, traversing two layers of strings, the first layer is forward, the second layer is reverse, and then for example, if the first layer is a left parenthesis, the second layer must be a right parenthesis.

but! The interviewer suggested that this can only judge the situation of {[()]}

Answer for the third time:

Zhuo! ! What the hell, I'm confused. Suddenly I had an idea and thought of finding the matching brackets one by one, and then delete the matching brackets from the string, and finally see what is left of the string.

At this moment, the interviewer also reminded me that I can think about changing the data structure and consider using a stack. In fact, my idea is basically the same as the stack, but not. . .

correct answer:

var isValid = function(s) {
    const n = s.length;
    if (n % 2 === 1) {
        return false;
    }
    const pairs = new Map([
        [')', '('],
        [']', '['],
        ['}', '{']
    ]);
    const stk = [];
    for (let ch of s){
        if (pairs.has(ch)) {
            if (!stk.length || stk[stk.length - 1] !== pairs.get(ch)) {
                return false;
            }
            stk.pop();
        } 
        else {
            stk.push(ch);
        }
    };
    return !stk.length;
};


At this point, the handwriting questions are over, and then some technical questions are asked:

6. Talk about the diff algorithm

My answer:

1. Vue's diff algorithm is to compare from both sides to the middle node. And a double pointer is used to update while comparing. React's diff algorithm is compared from left to right. During the comparison, the changed nodes are generated into a patch tree, and the patch is applied after the comparison.

2. The diff algorithm generally needs to specify the node key, that is, the unique value, so that the accuracy of the diff comparison can be ensured after the node is deleted or sorted.

3. Compared with vue2, the diff algorithm of vue3 is optimized. It will judge whether each node is a dynamic node during the compilation stage. By checking whether there are symbols like v-on, :class, etc. on the node, and then collect dynamic nodes to generate a block tree. When the dom changes, it will only compare the block tree. Because vue3 has made static improvements to static nodes, static nodes will only be rendered once.

4. The diff algorithm of vue3 also uses patchFlag to mark dynamic nodes to more efficiently determine what has been modified.

7. The process of entering the url to the page display

1. When the url is not entered completely, search for bookmarks, history records, etc., you can intelligently prompt and complete the address

2. Since the input is a domain name, the ip address mapped to the domain name must be resolved first. Therefore, DNS resolution must be performed first, first to see if there is any browser cache, if not, request the local DNS server, that is, the local operator, before requesting the root DNS server, then the top-level domain name server, and finally the authoritative domain name server. until you find it.

3. After parsing the ip address, make a tcp connection

4. The browser network process initiates a request, three-way handshake to request data, and after getting the data, wave four times to release the tcp connection

5. The browser browser process is ready to start rendering, and when ready, the ipc process communicates to notify the rendering process to start rendering

6. The rendering process starts rendering, first parses the html, generates a dom tree, then parses the css rules, generates a css tree, and then combines to generate a render tree. At this time, the render tree will remove the head tag and the display: none node, so it is not exactly the same as the dom tree structure. Final layout, drawing.

8. The working process of webpack, and what things have been used in webpack

In terms of the working process, I may not have understood it right at the time, and said something about the ast abstract syntax tree. It should actually say this:

  • compile start compiling
  • make Analyze the module and its dependent modules from the entry point, creating those module objects
  • build-module building blocks
  • after-compile complete build
  • seal Package build results
  • emit Output each chunk to the result file
  • after-emit complete output

Then use what I said:

1. Configure the loader of svg or something

2. Open sourcemap

3. Enable gzip compression

4. Configure cross-domain

5. Subcontracting

6. Install the plugin

7. Third-party libraries are loaded on demand

at last

If there is something wrong or something to add, please correct or add!

Guess you like

Origin blog.csdn.net/qq_38974163/article/details/124218610