Home Web Front-end JS Tutorial Detailed code explanations of the three most common problems in JavaScript

Detailed code explanations of the three most common problems in JavaScript

Mar 23, 2017 pm 02:49 PM

JavaScript is the official language of all modern browsers. Therefore, JavaScript issues arise in During interviews with various developers. This article mainly shares with you the three most common interview questions in JavaScript. Friends who need it can refer to it. Let’s take a look.

Preface

This article is not about the latest JavaScript libraries, daily development practices, or any new ES6 functions

On the contrary, it is often the case when discussing JavaScript. These 3 questions come up in interviews. I have been asked these questions myself, and my friends have told me that they have been asked too.

Of course, you should not only learn these 3 before the JavaScript interview. Questions – There are many ways to better prepare for your upcoming interview – but here are 3 questions your interviewer may ask to determine your understanding of the JavaScript language and mastery of the DOM

Let's get started! Please note that we will be using native JavaScript in the examples below because your interviewer will usually want to see what you are doing without the help of a third-party library (such as

jQuery

). How to understand JavaScript and DOM.

##Question #1: Event delegation

Note: Also called event delegation, time proxy, etc. ;

When building an application, sometimes you need to bind event listeners to buttons, text, or images on the page to perform certain actions when the user interacts with the element ##. #If we take a simple to-do list as an example, the interviewer may tell you that they expect certain actions to be performed when the user clicks on one of the list items. They want you to use JavaScript to implement this function. Assume that the HTML code is as follows:

<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>
Copy after login

You may want to bind an event listener to the element as follows:

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);
 });
 }
 
});
Copy after login

While this works, the problem is that you're binding event listeners to each list item individually. That's 4 elements, not a big deal, but if someone adds 10,000 to their to-do list. What to do (they may have a lot to do)? Then your function will create 10,000 independent event listeners and bind each event listener to the DOM. This code execution is very inefficient. In interviews, it's a good idea to first ask the interviewer what is the maximum number of items the user can enter. If it never exceeds 10, the above code will work fine. However, if there is no limit to the number of items the user can enter, then you should use a more efficient solution.

If your application may end up with hundreds of event listeners, a more efficient solution would be to actually bind one event listener to the entire container and then have access to each event listener when actually clicked an exact element. This is called event delegation, and it makes it more efficient to bind event handlers individually to each element.

Code using event delegation:

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);
 }
 });
 
});
Copy after login

Question #2: Using closures inside loops

Closures often come up in interviews so that the interviewer can gauge your familiarity with the language and whether you know when to use closures.

The essence of a closure is an internal function

accessing variables outside its scope. Closures can be used to implement things like private variables and creating factory functions. A common interview question about using closures goes like this:

Write a function that will loop through a list of integers and print the index of each element after a 3 second delay. The most common (but incorrect) way I see this problem is with an implementation like this:

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);
}
Copy after login

If you run the above code, after a 3 second delay you will See, the printed output is actually 4 each time, instead of the expected 0, 1, 2, 3.

To properly understand why this happens, it's useful to be in JavaScript, which is what the interviewer really intended.

The reason is that the setTimeout function creates a function that can access its outer scope (that is, what we often call a closure), and each loop contains the index i.

After 3 seconds, the function is executed and prints out the value of i, which is 4 at the end of the loop because its loop cycle has gone through 0,1,2,3,4, and the loop finally stops at 4 .

There are actually several correct ways to write to solve this problem. Two are listed below:

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);
}
Copy after login
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);
}
Copy after login

Question #3: Function anti-shake (Debouncing)


有一些浏览器事件可以在很短的时间内快速启动多次,例如调整窗口大小或向下滚动页面。例如,如果将事件侦听器绑定到窗口滚动事件上,并且用户继续非常快速地向下滚动页面,你的事件可能会在3秒的范围内被触发数千次。这可能会导致一些严重的性能问题。

如果你在面试中讨论构建应用程序和事件,如滚动,窗口调整大小,或键盘按下的事件时,请务必提及 函数防抖动(Debouncing) 和/或 函数节流(Throttling)来提升页面速度和性能。一个真实的案例,来自 guest post on css-tricks:

在2011年,一个问题在Twitter上被提出:当你滚动Twitter feed时,它会会变得非常慢甚至未响应。John Resig 就这个问题发布了一篇博文,它解释了直接绑定函数到scroll事件上是多么糟糕的事。

函数防抖动(Debouncing) 是解决这个问题的一种方式,通过限制需要经过的时间,直到再次调用函数。一个正确实现函数防抖的方法是:把多个函数放在一个函数里调用,隔一定时间执行一次。这里有一个使用原生JavaScript实现的例子,用到了作用域、闭包、this和定时事件:

// debounce函数用来包裹我们的事件
function debounce(fn, delay) {
 // 持久化一个定时器 timer
 let timer = null;
 // 闭包函数可以访问 timer
 return function() {
 // 通过 &#39;this&#39; 和 &#39;arguments&#39;
 // 获得函数的作用域和参数
 let context = this;
 let args = arguments;
 // 如果事件被触发,清除 timer 并重新开始计时
 clearTimeout(timer);
 timer = setTimeout(function() {
 fn.apply(context, args);
 }, delay);
 }
}
Copy after login

当这个函数绑定在一个事件上,只有经过一段指定的时间后才会被调用。

你可以像这样去使用这个函数:

// 当用户滚动时函数会被调用
function foo() {
 console.log(&#39;You are scrolling!&#39;);
}
 
// 在事件触发的两秒后,我们包裹在debounce中的函数才会被触发
let elem = document.getElementById(&#39;container&#39;);
elem.addEventListener(&#39;scroll&#39;, debounce(foo, 2000));
Copy after login

函数节流是另一个类似函数防抖的技巧,除了使用等待一段时间再调用函数的方法,函数节流还限制固定时间内只能调用一次。所以一个事件如果在100毫秒内发生10次,函数节流会每2秒调用一次函数,而不是100毫秒内全部调用。

总结

The above is the detailed content of Detailed code explanations of the three most common problems in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to solve the problem that jQuery cannot obtain the form element value How to solve the problem that jQuery cannot obtain the form element value Feb 19, 2024 pm 02:01 PM

To solve the problem that jQuery.val() cannot be used, specific code examples are required. For front-end developers, using jQuery is one of the common operations. Among them, using the .val() method to get or set the value of a form element is a very common operation. However, in some specific cases, the problem of not being able to use the .val() method may arise. This article will introduce some common situations and solutions, and provide specific code examples. Problem Description When using jQuery to develop front-end pages, sometimes you will encounter

What are the questions in the Rulong 8 Wine Master exam? What are the questions in the Rulong 8 Wine Master exam? Feb 02, 2024 am 10:18 AM

What are the questions involved in the Yulong 8 Wine Master exam? What is the corresponding answer? How to pass the exam quickly? There are many questions that need to be answered in the Master of Wine Examination activities, and we can refer to the answers to solve them. These questions all involve knowledge of wine. If you need a reference, let’s take a look at the detailed analysis of the answers to the Yakuza 8 Wine Master exam questions! Detailed explanation of answers to questions in the Rulong 8 Wine Master exam 1. Questions about "wine". This is a distilled liquor produced by a distillery established by the royal family. It is brewed from the sugar of sugarcane grown in large quantities in Hawaii. What is the name of this wine? Answer: Rum 2. Question about "wine". The picture shows a drink made from dry ginseng and dry vermouth. It is characterized by the addition of olives and is known as "cockney"

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

See all articles