Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the questions that are often asked in Javascript interviews?

2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "what are the questions often asked in the Javascript interview". The explanation in the article is simple and clear, and is easy to learn and understand. Please follow the editor's train of thought to study and learn "what are the questions often asked in the Javascript interview?"

Question 1: event principal-agent

When building an application, it is sometimes necessary to bind events 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 to perform certain actions when the user clicks on a list item in the list. They want you to do this in JavaScript, assuming the following HTML code:

Walk the dog Pay bills Make dinner Code for one hour

You may want to do the following to bind an event to an element:

Document.addEventListener ('DOMContentLoaded', function () {let app = document.getElementById (' todo-app'); let itimes = app.getElementsByClassName ('item'); for (let item of items) {item.addEventListener (' click', function () {alert ('you clicked on item:' + item [XSS _ clean]);})})

While this is technically feasible, the problem is to bind events to each item separately. This is not a big problem for the current four elements, but what if 10000 items are added to the to-do list (they may have a lot to do)? The function then creates 10000 separate event listeners and binds each event listener to DOM, which makes code execution very inefficient.

In an interview, * first ask the interviewer how many * * elements the user can enter. For example, if it is no more than 10, then the above code works well. But if there is no limit to the number of entries that users 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 is to actually bind an event listener to the entire container, and then be able to access each list item when you click it, which is called an event delegate. it is more efficient than attaching a separate event handler.

Here is the code for the event delegate:

Document.addEventListener ('DOMContentLoaded', function () {let app = document.getElementById (' todo-app'); app.addEventListener ('click', function (e) {if (e.target & & e.target.nodeName =' LI') {let item = e.target; alert ('you clicked on item:' + item [XSS _ clean])})})

Problem 2: using closures in loops

Closures often appear in interviews so that the interviewer can measure how familiar you are with JS and whether you know when to use closures.

A closure is basically a variable that an internal function can access outside its scope. Closures can be used to achieve privacy and create function factories. Common interview questions for closures are as follows:

Write a function that iterates through the list of integers and prints the index of each element after a delay of 3 seconds.

The often incorrect way of writing goes like this:

Const arr = [10,12,15,21]; for (var I = 0; I

< arr.length; i++) { setTimeout(function() { console.log('The index of this number is: ' + i); }, 3000); } 如果运行上面代码,3 秒延迟后你会看到,实际上每次打印输出是 4,而不是期望的 0,1,2,3 。 为了正确理解为什么会发生这种情况,了解为什么会在 JavaScript 中发生这种情况将非常有用,这正是面试官试图测试的内容。 原因是因为 setTimeout 函数创建了一个可以访问其外部作用域的函数(闭包),该作用域是包含索引 i 的循环。 经过 3 秒后,执行该函数并打印出 i 的值,该值在循环结束时为 4,因为它循环经过0,1,2,3,4并且循环最终停止在 4。 实际上有多处方法来正确的解这道题: const arr = [10, 12, 15, 21]; for (var i = 0; i < arr.length; i++) { setTimeout(function(i_local){ return function () { console.log('The index of this number is: ' + i_local); } }(i), 3000) }const arr = [10, 12, 15, 21]; for (let i = 0; i < arr.length; i++) { setTimeout(function() { console.log('The index of this number is: ' + i); }, 3000); } 问题 3:事件的节流(throttle)与防抖(debounce) 有些浏览器事件可以在短时间内快速触发多次,比如调整窗口大小或向下滚动页面。例如,监听页面窗口滚动事件,并且用户持续快速地向下滚动页面,那么滚动事件可能在 3 秒内触发数千次,这可能会导致一些严重的性能问题。 如果在面试中讨论构建应用程序,出现滚动、窗口大小调整或按下键等事件请务必提及 防抖(Debouncing) 和 函数节流(Throttling)来提升页面速度和性能。这两兄弟的本质都是以闭包的形式存在。通过对事件对应的回调函数进行包裹、以自由变量的形式缓存时间信息,***用 setTimeout 来控制事件的触发频率。 Throttle: ***个人说了算 throttle 的主要思想在于:在某段时间内,不管你触发了多少次回调,都只认***次,并在计时结束时给予响应。 这个故事里,‘裁判’ 就是我们的节流阀, 他控制参赛者吃东西的时机, "参赛者吃东西"就是我们频繁操作事件而不断涌入的回调任务,它受 "裁判" 的控制,而计时器,就是上文提到的以自由变量形式存在的时间信息,它是 "裁判" 决定是否停止比赛的依据,***,等待比赛结果就对应到回调函数的执行。 总结下来,所谓的"节流",是通过在一段时间内无视后来产生的回调请求来实现的。只要 裁判宣布比赛开始,裁判就会开启计时器,在这段时间内,参赛者就尽管不断的吃,谁也无法知道最终结果。 对应到实际的交互上是一样一样的:每当用户触发了一次 scroll 事件,我们就为这个触发操作开启计时器。一段时间内,后续所有的 scroll 事件都会被当作"参赛者吃东西——它们无法触发新的 scroll 回调。直到"一段时间"到了,***次触发的 scroll 事件对应的回调才会执行,而"一段时间内"触发的后续的 scroll 回调都会被节流阀无视掉。 现在一起实现一个 throttle: // fn是我们需要包装的事件回调, interval是时间间隔的阈值 function throttle(fn, interval) { // last为上一次触发回调的时间 let last = 0 // 将throttle处理结果当作函数返回 return function () { // 保留调用时的this上下文 let context = this // 保留调用时传入的参数 let args = arguments // 记录本次触发回调的时间 let now = +new Date() // 判断上次触发的时间和本次触发的时间差是否小于时间间隔的阈值 if (now - last >

= interval) {/ / if the time interval is greater than the interval threshold we set, execute the callback last = now; fn.apply (context, args);} / / wrap the callback of scroll with throttle const better_scroll = throttle (() = > console.log ('scroll event triggered'), 1000) document.addEventListener ('scroll', better_scroll)

Debounce: * one contestant has the final say

The main idea of anti-shaking is: I will wait for you to the end. In a certain period of time, no matter how many callbacks you trigger, I only recognize it once.

To continue the story of the king of appetite competition, this time there is no time limit, the contestants can't eat until they can't eat, when no one is eating in the next 10 minutes, if no one is eating in the next 10 minutes, if anyone can still eat in 10 minutes, the game continues until the next 10 minutes when no one is eating.

Compare throttle to understand debounce: in throttle's logic, the 'referee' has the final say and executes the callback function when the game time is up. Debounce believes that a contestant has the final say and will reset the new timer as long as there is still food to eat.

Now let's implement a debounce:

/ / fn is the event callback we need to wrap, and delay is the waiting time function debounce (fn) for each deferred execution. Delay) {/ / timer let timer = null / / returns the debounce processing result as a function to return function () {/ / retain the this context of the call let context = this / / the parameter passed in when the call is let args = arguments / / each time the event is triggered All clear the old timer if (timer) {clearTimeout (timer)} / / set up a new timer timer = setTimeout (function () {fn.apply (context, args)}, delay)}} / / wrap the callback of scroll with debounce const better_scroll = debounce (() = > console.log ('scroll event triggered'), 1000) document.addEventListener ('scroll' Better_scroll)

Optimize Debounce with Throttle

The problem with debounce is that it is "too patient". Imagine that if a user acts frequently-he does the next operation each time without waiting for the end of the delay time set by debounce, so each time debounce regenerates a timer for that user, and the callback function is delayed countless times. Frequent delays will cause users to get no response, and users will also have the impression that "this page is stuck".

In order to avoid self-defeating, we need to borrow the idea of throttle to create a "bottom line" debounce-- and so on, but I have my principle: within delay time, I can regenerate the timer for you; but as long as the delay time is up, I have to give the user a response. This "integration" of throttle and debounce has been applied to the implementation of their enhanced throttle functions by many mature front-end libraries:

/ / fn is the event callback we need to wrap, delay is the threshold of the time interval function throttle (fn, delay) {/ / last is the time when the last callback was triggered, and timer is the timer let last = 0 Timer = null / / return the throttle processing result as a function to return function () {/ / preserve the this context of the call let context = this / / retain the parameter passed in during the call let args = arguments / / record the time of this callback let now = + new Date () / / determine the time of the last trigger and this Whether the time difference of the second trigger is less than the threshold if of the time interval (now-last)

< delay) { // 如果时间间隔小于我们设定的时间间隔阈值,则为本次触发操作设立一个新的定时器 clearTimeout(timer) timer = setTimeout(function () { last = now fn.apply(context, args) }, delay) } else { // 如果时间间隔超出了我们设定的时间间隔阈值,那就不等了,无论如何要反馈给用户一次响应 last = now fn.apply(context, args) } } } // 用新的throttle包装scroll的回调 const better_scroll = throttle(() =>

Console.log ('triggered scrolling event'), 1000) document.addEventListener ('scroll', better_scroll) Thank you for your reading. The above is the content of "what are the questions often asked in Javascript interviews?" after the study of this article, I believe you have a deeper understanding of the questions often asked in Javascript interviews, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report