Common interview Questions in JS-notes

Source: Internet
Author: User


Original reference Https://mp.weixin.qq.com/s/mCVL6qI33XeTg4YGIKt-JQ

1. Event Broker
Adds an event to the parent element, using the event bubbling principle, to get child elements based on E.target
<ul id= "Parentbox" >
<li class= "Item" >1</li>
<li class= "Item" >2</li>
<li class= "Item" >3</li>
</ul>
Let Parentbox = document.getElementById (' Parentbox ');
Parentbox.addeventlistener (' click ', Function (e) {
if (e.target && e.target.nodename = = = ' LI ') {
Let item = E.target;
Console.log (item);
}
})
2. Using closures in loops
var arr = [1,2,3,4,5];
for (var i=0; i<arr.length; i++) {
SetTimeout (function () {
Console.log (i)
},1000)
}
The output is: 5,5,5,5,5
Want to let I output 0,1,2,3,4
Method one using closures
for (var i=0; i<arr.length; i++) {
SetTimeout (function (j) {//Here the value is passed in
Console.log (j)//Accept Here
} (i), 1000)//use of closures
}
Method two let keyword
for (let i=0; i<arr.length; i++) {
Settimout (function () {
Console.log (i)
},1000)
}
3. When scrolling the page and window adjustment, the event is triggered.
The core idea is to use the settimeout delay function to handle events.
Parameter one accepts execution function, parameter two delay time
function Debounce (fn,delay) {
Maintain a timer
let timer = null;
A closure that can access the timer
return function () {
Get the scope and variables of a function through this and arguments
let context = this;
let args = arguments;
If the event is called, clear the timer and then reset the timer
Cleartimeout (timer);
Timer = setTimeout (function () {
Fn.apply (Context,args);
},delay);
}
}

Common interview Questions in JS-notes

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.