Home  >  Article  >  Web Front-end  >  3 JavaScript Interview Questions to Pay Attention to

3 JavaScript Interview Questions to Pay Attention to

怪我咯
怪我咯Original
2017-04-05 14:00:391262browse

JavaScript is the official language of all modern browsers. As a result, JavaScript questions are asked in developer interviews in various languages.

This article does not cover the latest JavaScript libraries, common development practices, or any new ES6 functions. Instead, let’s talk about 3 JavaScript questions that often come up in interviews. I asked these questions and my friends said they asked them too.

Of course this does not mean that you only need to learn these 3 questions when preparing for a JavaScript interview - you still have many ways to better prepare for the upcoming interview - but the interviewer is very likely to pass the following 3 questions To determine your understanding and mastery of JavaScript and DOM.

let's start! Note that we use native JavaScript in the examples below because interviewers usually want to test how well you understand JavaScript and the DOM without the help of a library (such as jQuery).

Question #1: Event Broker

When creating an application, sometimes you need to add event listeners to buttons, text, or pictures on the page, and trigger certain operations when the user interacts with these elements. .

Let’s take a simple to-do list as an example. The interviewer will tell you that they want to trigger an action when the user clicks on an item in the list. And let you use JavaScript to implement this function according to the following HTML code:

<ul id="todo-app">
  <li class="item">Walk the dog</li>
  <li class="item">Pay bills</li>
  <li class="item">Make dinner</li>
  <li class="item">Code for one hour</li>
</ul>

You may add event listeners to elements like the following code:

document.addEventListener(&#39;DOMContentLoaded&#39;, function() {

  let app = document.getElementById(&#39;todo-app&#39;);
  let items = app.getElementsByClassName(&#39;item&#39;);

  // 给每个列表项添加事件监听器
  for (let item of items) {
    item.addEventListener(&#39;click&#39;, function() {
      alert(&#39;you clicked on item: &#39; + item.innerHTML);
    });
  }

});

Of course the above code can complete the interview According to the official's needs, the problem is that each list item will be added with an event listener. This is fine when the list only has 4 items, but what if someone adds 10,000 items to their to-do list (maybe they have a lot to do)? At that point the function will create 10,000 event listeners and add them all to the DOM. This efficiency is very low. During the interview, it is best to first ask the interviewer how many to-do items a user can add at most. If there are never more than 10, then the above code will run without issue. But if there is no limit to the number of to-do items a user can enter, then you have to find a more efficient solution.

If the application has hundreds of event listeners, a more efficient solution is to add

an

event listener to the outermost container, and then get the actual event listener when the user actually clicks The clicked to-do item. This is called an event delegate and is more efficient than adding separate event listeners to each to-do item. Here is the code for the event proxy:

document.addEventListener(&#39;DOMContentLoaded&#39;, function() {

  let app = document.getElementById(&#39;todo-app&#39;);

  // 给容器添加事件监听器
  app.addEventListener(&#39;click&#39;, function(e) {
    if (e.target && e.target.nodeName === &#39;LI&#39;) {
      let item = e.target;
      alert(&#39;you clicked on item: &#39; + item.innerHTML);
    }
  });

});

Question #2: Using closures in loops

Closures are often asked in interviews because the interviewer can pass this Answers to the questions gauge your familiarity with the language and test whether you know when to use closures.

A closure is an

internal function

that can access variables outside the scope. Closures can be used to implement privatization and create factory functions. Common interview questions about closures are as follows: Write a function that loops over an

integer

array, and prints the index of each element in the array with a delay of 3 seconds. . The common (incorrect) implementation of this problem is as follows:

const arr = [10, 12, 15, 21];
for (var i = 0; i < arr.length; i++) {
  setTimeout(function() {
    console.log(&#39;The index of this number is: &#39; + i);
  }, 3000);
}

If you run this function, you will find that

4## is printed every time after 3 seconds. # instead of the expected

0, 1, 2, 3. In order to correctly find the reason for this situation, you need to understand how JavaScript runs this code, which is what the interviewer wants to examine you.

The reason is that the setTimeout function creates a function (closure) that accesses the outer scope, which is the loop containing index i. After 3 seconds, the function starts to print the value of i, and the loop ends at this time, and the value of i is already 4. Because after looping through 0, 1, 2, 3, 4, it finally stops at 4.

There are actually several ways to correctly solve this problem. Here are two:

const arr = [10, 12, 15, 21];
for (var i = 0; i < arr.length; i++) {
  // 给每个函数传入变量 i 让其能访问正确的索引
  setTimeout(function(i_local) {
    return function() {
      console.log(&#39;The index of this number is: &#39; + i_local);
    }
  }(i), 3000);
}
const arr = [10, 12, 15, 21];
for (let i = 0; i < arr.length; i++) {
  // 使用 ES6 中的 let 关键字,它会在函数调用时创建一个新的绑定
  // 了解更多:http://exploringjs.com/es6/ch_variables.html#sec_let-const-loop-heads
  setTimeout(function() {
    console.log(&#39;The index of this number is: &#39; + i);
  }, 3000);
}

Question #3: Debouncing

Some browser events can be triggered multiple times in a short period of time, such as window resizing or scrolling page. If you add an event listener to the window scroll event, and the user keeps scrolling down the page quickly, your event may be fired thousands of times in 3 seconds. This can cause very serious performance issues.

If the interview discusses building applications and scroll events, window resize events, or keyboard events, etc., be sure to mention debouncing or throttling as a way to improve page speed and performance. Let’s take an example of css-tricks:

In 2011, Twitter had a problem: when scrolling the Twitter summary, the page became very stuck or even unresponsive. John Resig wrote a blog about this issue, explaining how binding time-consuming functions directly to the scroll event is a bad idea.

Debouncing 是解决这个问题的一种方法,它的做法是限制下次函数调用之前必须等待的时间间隔。正确实现 debouncing 的方法是将若干个函数调用 合成 一次,并在给定时间过去之后仅被调用一次。下面是一个原生 JavaScript 的实现,用到了 作用域 , 闭包, this , 和 计时事件 :

// 将会包装事件的 debounce 函数
function debounce(fn, delay) {
  // 维护一个 timer
  let timer = null;
  // 能访问 timer 的闭包
  return function() {
    // 通过 ‘this’ 和 ‘arguments’ 获取函数的作用域和变量
    let context = this;
    let args = arguments;
    // 如果事件被调用,清除 timer 然后重新设置 timer
    clearTimeout(timer);
    timer = setTimeout(function() {
      fn.apply(context, args);
    }, delay);
  }
}

这个函数 — 当传入一个事件(fn)时 — 会在经过给定的时间(delay)后执行。

函数这样用:

// 当用户滚动时被调用的函数
function foo() {
  console.log(&#39;You are scrolling!&#39;);
}

// 在 debounce 中包装我们的函数,过 2 秒触发一次
let elem = document.getElementById(&#39;container&#39;);
elem.addEventListener(&#39;scroll&#39;, debounce(foo, 2000));

Throttling 是与 debouncing 类似的一种技术,但它不是在调用函数之前等待一段时间,throttling 是在较长的时间间隔内调用函数。所以如果一个事件每 100 毫秒被触发 10 次,throttling 会在每隔 2 秒时执行一次这个函数,而不是在 100 毫秒内执行 10 次事件。

 

The above is the detailed content of 3 JavaScript Interview Questions to Pay Attention to. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn