JavaScript interview questions are enough to read this one, simple and comprehensive (continuously update step2)

1. How to solve the infinite loop problem caused by dynamically adding divs in the loop?

Expression ①:

let divs = document.getElementsByTagName("div");
for(let i = 0;i<divs.length;++i){
    
    
	let div = document.createElement("div");
	document.body.appendChild(div);
}

Expression ②:

let divs = document.getElementsByTagName("div");
for(let i = 0,len=divs.length;i<len;++i){
    
    
	let div = document.createElement("div");
	document.body.appendChild(div);
}

<div>The first line in expression ① gets an HTMLCollection that contains all the elements in the document. Because this collection is live, any time you add a new <div>element to the page, querying the collection will add one more item. Because the browser does not want to save the collection every time it is created, it updates the collection every time it is accessed. It is evaluated each time through the loop i < divs.length, which means a query to get all <div>elements. Because the loop body creates and adds a new <div>element to the document, the value of divs.length is also incremented each time the loop is looped. Since both values ​​are incremented, i will never be equal divs.length, so expression ① creates an infinite loop.
In expression ②, a variable len that stores the length of the set is initialized, because len stores the length of the set at the beginning of the loop, and this value will not grow dynamically with the increase of the set ( for循环中初始化变量处只会初始化一次), so it can be avoided in expression ①. infinite loop problem.
If you don't want to initialize a variable, you can also use reverse iteration:

Expression ③:

let divs = document.getElementsByTagName("div");
for(let i = divs.length-1;i>=0;--i){
    
    
	let div = document.createElement("div");
	document.body.appendChild(div);
}

Second, talk about the performance of innerHTML?

1. Use the negative teaching material of innerHTML

for(let value of values){
    
    
	ul.innerHTML += '<li>${value}</li>';
}

This code is inefficient because the innerHTML needs to be set once for each iteration, and not only that, but the innerHTML is read first in each loop, which means that the innerHTML is accessed twice in one loop.

2. Improve code efficiency

let itemsHtml = "";
for(let value of values){
    
    
	itemsHtml  += '<li>${value}</li>';
}
ul.innerHTML = itemsHtml;

After this modification, the efficiency is much higher, and only one assignment is made to innerHTML, and the following code can also be done:
ul.innerHTML = values.map(value => '<li>${value}</li>').join(' ');

3. How to solve the problem of too many similar buttons?

The solution to too many event handlers is to use event delegation. Event delegation takes advantage of event bubbling, allowing only one event handler to manage one type of event. For example, the click event bubbles up to the document. This means that one onclick event handler can be specified for the entire page, rather than a separate event handler for each clickable element.

<ul id="myGirls">
	<li id="girl1">比比东</li>
	<li id="girl2">云韵</li>
	<li id="girl3">美杜莎</li>
</ul>

This contains three list items that should perform some action when clicked, usually by specifying three event handlers:

let item1 = document.getElementById("girl1");
let item2 = document.getElementById("girl2");
let item3 = document.getElementById("girl3");

item1.addEventListener("click",(event) => {
    
    
	console.log("我是比比东!");
})

item2.addEventListener("click",(event) => {
    
    
	console.log("我是云韵!");
})

item3.addEventListener("click",(event) => {
    
    
	console.log("我是美杜莎!");
})

The same code is too much, the code is too ugly.
Using event delegation, just add an event handler to the common ancestor node with multiple elements, and you can solve the ugliness!

let list = document.getElementById("myGirls");
list.addEventListener("click",(event) => {
    
    
	let target = event.target;
	switch(target.id){
    
    
		case "girl1":
			console.log("我是比比东!");
			break;
		case "girl2":
			console.log("我是云韵!");
			break;
		case "girl3":
			console.log("我是美杜莎!");
			break;
	}
})

4. What are the advantages of event delegation?

  1. The document object is available at any time, and you can add an event handler to it at any time (without waiting for DOMContentLoaded or load events) to handle all events of some type in the page. This means that as long as the page renders the clickable element, it works without delay.
  2. Save events spent on setting page event routines.
  3. Reduces the memory required for the entire page and improves overall performance.
    5. How did you solve the secondary submission of the form?
    Avoid extra submitted code:
let form = document.getElementById("myForm");
for.addEventListener("submit",(event) => {
    
    
	let target = event.target;
	let btn = target.elements["submit"];
	btn.disabled = true;
});

The above code registers an event handler on the submit event of the form, and when the submit event fires, the code gets the submit button and then sets its disabled property to true. Note that this feature cannot be achieved by adding an onclick event handler directly to the submit button, because the timing of the event is different in different browsers. Some browsers will trigger the click event of the submit button before triggering the submit event of the form, and some browsers will trigger the click event later. For browsers that trigger the click event first, the button will be disabled before the form is submitted, which Means the form will not be submitted. So it's better to use the form's submit event to disable the submit button.

5. JavaScript Mind Map

insert image description here

Pay attention to the public number: Nezha programming

Nezha programming updates high-quality articles every week. After paying attention, reply to [CSDN] to receive Java mind maps, Java learning materials, and massive interview materials.


Add me WeChat: 18525351592

Pull you into the technical exchange group, there are many technical bigwigs in the group, exchange technology together, advance together, enter the big factory together, and also buy technical books for free~~

Guess you like

Origin blog.csdn.net/guorui_java/article/details/123610568