A classic JS face questions

More than 80% of the candidates on the Road to answer the following circumstances JS face questions even pass the total. This is what is a magical JS face questions? He examines what the candidates' ability? What are the implications of this article you are reading?

 

Humble start

Recruitment front-end engineers, especially senior front-end engineer, JS solid foundation is absolutely necessary condition, not a solid foundation engineers in the face of various problems in the high probability front-end development will be helpless. During the inspection candidate JS basis, I often provide the following piece of code, and then analyze the results of its candidates to the actual operation of:

for (var i = 0; i < 5; i++) {
 setTimeout(function() {
  console.log(new Date, i);
 }, 1000);
}

console.log(new Date, i);

This code is very short, only seven lines, I think, should be able to read the students here you do not need me to explain what the code line by line to do it. The results given in the face of this code are not the same candidate, the following is a typical answer:

A. 20% of people quickly scan code, and gives the result: 0,1,2,3,4,5;
B. 30% of the people holding the code line by line to see and gives the result: 5,0 , 1,2,3,4;
C. 50% of people will hold the code digest, and then gives the result: 5,5,5,5,5,5;

As long as you JS synchronous and asynchronous difference codes, variable scope, the concept of closures, which are properly understood, they know the correct answer is C, the actual output of the code is:

2017-03-18T00:43:45.873Z 5
2017-03-18T00:43:46.866Z 5
2017-03-18T00:43:46.868Z 5
2017-03-18T00:43:46.868Z 5
2017-03-18T00:43:46.868Z 5
2017-03-18T00:43:46.868Z 5

Next, I would ask: if we agreed with the arrow indicates a 1-second interval between the two output before and after, and a comma represents the time between two output before and after the interval can be ignored, the resulting code is actually running how to describe? There will be the following two answers:

A. 60% of people will be described as follows: 5 -> 5 -> 5 -> 5 -> 5, i.e. has a one second interval between each 5;
B. 40% of people will be described as follows: 5 - > 5,5,5,5,5, ie a direct output 5, after one second, five output 5;

This requires candidates to JS in the timer mechanism is very familiar with the process loop is executed, almost at the same time set up five timers, under normal circumstances, these timers will be triggered after one second, and the cycle is finished output immediate execution, obviously, the correct description is B.

If you fail to be here, then, 100 people participated in the interview that only 20 people can pass, read the students here can think carefully, you pass it?

1 asked: Closures

If this question is to examine only candidate for JS asynchronous code, variable scope understand the limitations of too much, then I would ask, if the desired output of the code becomes: 5 -> 0,1,2,3 4, how to transform the code? Familiar closure students will soon be able to give the following solution:

for (var i = 0; i < 5; i++) {
 (function(j) { // j = i
  setTimeout(function() {
   console.log(new Date, j);
  }, 1000);
 })(i);
}

console.log(new Date, i);

Clever use of IIFE (Immediately Invoked Function Expression: a statement that the implementation of a function expression) to solve the problem caused by the closures, is indeed a good idea, but beginners may not think this code easy to understand, at least the early entry of the author when pondering for a moment here really understand.

Is there a more intuitive approach? The answer is, we just need a little play tricks on the body of the loop, so that code is responsible for the output value i can get to each cycle. how should I do it? JS using basic types (Primitive Type) parameter is passed by value characteristic (Pass by Value), and difficult to engineer the following code:

Output function = var (I) { 
 the setTimeout (function () { 
  the console.log (a Date new new, I); 
 }, 1000); 
}; 

for (var I = 0; I <. 5; I ++) { 
 Output (I); // here i-past value is copied 
} 

the console.log (a Date new new, i);

Candidates can give the above two solutions can be considered as the basis of understanding and application of JS is good, it can add 10 points each. Of course, there are the actual interview candidates given in the following code:

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

console.log(new Date, i);

Observant students will notice that there are only a very slight change, namely the use of ES6  block-level scope (Block Scope) is replaced let var, but the code will be in the actual run-time error, because the final output used in its i where the scope is not present, i exist only within a cycle.

Students can think ES6 features Although there is no answer, but demonstrated his understanding of the ES6, you can add 5 points, continue with the questioning.

Asked 2: ES6

Experienced front-end students read here may be some impatient, pulled so much, all he knew of the contents, first do not worry, the difficulty of the challenge will continue to increase.

Subsequently above continue to ask: if the desired code output becomes 0 -> 1 -> 2 -> 3 -> 4 -> 5, and requires the original code blocks and two cycles console.log unchanged, the how the transformation of the code? The new requirements can accurately be described as follows: When the code is executed, immediately outputs 0, then sequentially output every second, four, five outputs (used here probably in about 5 seconds after the end of the cycle time, is in order to avoid a dead end students fall into the trap, because the timer trigger JS occasion there may be uncertain, specifically refer to  How Javascript timers Work ).

See here, some students will be given the following feasible solution:

for (var I = 0; I <. 5; I ++) { 
 (function (J) { 
  the setTimeout (function () { 
   the console.log (new new a Date, J); 
  }, 1000 * J)); // 0 ~ where modification timer 4 
 }) (I); 
} 

the setTimeout (function () {// here increase timer timeout to 5 seconds for 
 the console.log (a Date new new, I); 
}, I * 1000);

Have to admit, this approach is effective, although rough, but not be able to add additional points program. If this demand is the abstract: Complete Series asynchronous operation (each cycle produces an asynchronous operation) after, do other things, how the code of the organization? You are wise not to think of what? Yes, that's  Promise .

Some students might ask, is not that a few digital output it in the console? As this overkill? You know, the interviewer really wants to examine is whether the candidate has a certain capacity and quality, because in the modern front-end development, the code that handles asynchronous everywhere, familiar with and master the asynchronous operation of process control is to become a qualified developer basic skills.

Down down, it is easy to give solutions based Promise (Promise since it is ES6 new features, our new code written using ES6 is not better? If so you write a big probability will make the interviewer Heart goodwill):

Tasks = const []; 
for (var i = 0; i <. 5; i ++) {// statements where i is changed not let, how to do this if you want to change? 
 ((J) => { 
  tasks.push (new new Promise ((Resolve) => { 
   the setTimeout (() => { 
    the console.log (new new a Date, J); 
    Resolve (); // Here we must resolve, otherwise the code not expected Work 
   }, 1000 * J); // timer timeout increased progressively 
  })); 
 }) (I); 
} 

Promise.all (Tasks) .then (() => { 
 the setTimeout (() => { 
  the console.log (a Date new new, I); 
 }, 1000); // Note that just need to set the time-out 1 second 
});

In contrast, I prefer this looks more concise code below to know programming style is a lot of emphasis on the point of the interviewer, the particle size of the code when reading a smaller, more modular, it will undoubtedly be a plus point.

const tasks = []; // store where the asynchronous operation Promise 
const = Output (I) => new new Promise ((Resolve) => { 
 the setTimeout (() => { 
  the console.log (a Date new new, I); 
  Resolve ( ); 
 }, I * 1000); 
}); 

// generate all asynchronous operation 
for (var I = 0; I <. 5; I ++) { 
 ; tasks.push (Output (I)) 
} 

after the asynchronous operation is complete // , the output of the last I 
Promise.all (Tasks) .then (() => { 
 the setTimeout (() => { 
  the console.log (a Date new new, I); 
 }, 1000); 
});

Students read here, congratulations, your next interview encountered similar problems, you can earn at least 80 points.

We all know that the use of code than Promise handle asynchronous callback mechanism to make the code more readable, but using Promise problem is also evident that without reject treatment Promise, it will result in an error being thrown into a black hole , and fortunately the new version of Chrome Node 7.x can give abnormal untreated  unhandled Rejection Warning , and troubleshoot these errors require some special skills ( browser , Node.js ).

Asked 3: ES7

Now that you have seen here, it would insist on two minutes, the next content will make you understand your insistence is worth it.

Most of the interviewer before deciding to hire a candidate also need to look at another important capability that self-driving technology force, straightforward to say that there are internal candidates like motor drive him to solve problems in engineering field with a beautiful way , continue to follow the business and technology becomes more regressed, what is regressed? Suggested Reading program life this analysis .

Back to the topic, since the Promise has been won, how to use async await characteristics ES7 in to make this code becomes more simple? Are you able to give answers based on their current knowledge? Please pause here one minute, thinking the next.

The following reference code is given by the author:

// analog sleep in other languages, can be virtually any asynchronous operation 
const = sleep (timeountMS) => new new Promise ((Resolve) => { 
 the setTimeout (Resolve, timeountMS); 
}); 

(the async () => { // declare i.e. async executed function expression 
 for (var I = 0; I <. 5; I ++) { 
  the await SLEEP (1000); 
  the console.log (a Date new new, I); 
 } 

 the await SLEEP (1000); 
 the console.log (a Date new new, I); 
}) ();

 Article from: https: //www.jb51.net/article/109005.htm

Guess you like

Origin www.cnblogs.com/qiujianmei/p/11698799.html