2023 interview question records

1. How does js determine that an object is empty?

A simple way to tell if an object is null is to check all of the object's enumerable properties. If an object has no enumerable properties, then we can consider it empty. You can use  Object.keys() a function to get all enumerable properties of an object and then check the length of the resulting array. If the length is 0, then the object is empty.

function isEmpty(obj) {  
    return Object.keys(obj).length === 0 && obj.constructor === Object;  
}  
  
var myObj = {};  
  
if (isEmpty(myObj)) {  
    console.log("对象是空的");  
} else {  
    console.log("对象不是空的");  
}

2. API for obtaining the latest url parameters

For APIs that get URL parameters, you can use JavaScript’s URLSearchParams interface

const urlParams = new URLSearchParams(window.location.search);  
const myParam = urlParams.get('myParam');

3. After the new version is released, how to use technical means to notify users to refresh the page?

After a new version is released, you can use Web Push to notify users to refresh the page.

if ('serviceWorker' in navigator) {  
  navigator.serviceWorker.register('/service-worker.js')  
    .then(() => console.log('Service Worker Registered'))  
    .catch(err => console.log('Service Worker Registration Failed: ', err));  
}

4. How does the Vue project improve project performance?

  • Lazy loading: Use Vue's asynchronous components and Webpack's code splitting function to split large dependency files into small pieces and load them dynamically as needed.
  • Code splitting: Split large Vue components into multiple small components to reduce rendering time and memory usage.
  • Optimize images: Use compression and optimization tools like TinyPNG and ImageOptimizer to reduce image size and load time.

5. Cache

        5.1. Strong caching

        Force the browser to read data directly from the local cache within a certain period of time without sending a request to the server. Strong caching can be achieved by setting response header information. Common response headers include Expires and Cache-Control.

        5.2. Negotiate cache

        When the strong cache fails, the browser will send a request to the server to ask the server whether the resource has been modified since the last access. If there is no modification, the server will return a 304 status code, telling the browser that it can continue to use the local cache, otherwise it will return new resource content. Negotiation caching can be achieved by setting response header information. Common response headers include Last-Modified and ETag.

        5.3. The main process of browser caching can be summarized as the following steps:

            5.3.1. When the browser receives an HTTP request, it will determine whether the resource has been cached based on the URL. If it has been cached, the resource is read directly from the local cache.
            5.3.2. If it is not cached or the cache has expired, the browser will send a request to the server and bring some information in the request, such as the last access time, Etag, etc.
After the server receives the request, it determines whether the resource has been updated based on the information in the request. If the resource has not been updated, a 304 response code is returned, telling the browser that it can continue to use the local cache; if the resource has been updated, the new resource content and some cache-related header information are returned.
            5.3.3. After the browser receives the response, it will update the local cache based on the response header information and display the new resource content to the user.

6. The process of new constructor

  • Create an empty object.
  • Point the prototype of this new object to the prototype property of the constructor.
  • Execute the constructor and point this to the newly created object.
  • If the constructor returns no value or returns a non-object value, the newly created object is returned. If the constructor returns an object, this object is returned.
function myNew(ctor, ...args) {
	// 创建一个新对象,并将该对象的原型指向构造函数的原型对象
	const obj = Object.create(ctor.prototype);

	// 调用构造函数,并将新对象作为 this 参数传递进去
	const result = ctor.apply(obj, args);

	// 如果构造函数返回了一个非空对象,则返回该对象;否则,返回创建的新对象
	if (typeof result === 'object' && result !== null) {
		return result;
	}
	return obj;
}
// 测试:
function Person(name, age) {
	this.name = name;
	this.age = age;
}

const person = myNew(Person, '张三', 18);
console.log(person.name); // 输出:张三
console.log(person.age); // 输出:18

7、EventLoop

  1. The code starts executing, creating a global call stack, and the script is executed as a macro task.
  2. The execution process is executed immediately through synchronous tasks, and asynchronous tasks are registered to the microtask queue and macrotask queue according to the asynchronous task type.
  3. After the synchronization task is executed, check the microtask queue
    • If there are microtasks, execute all microtasks in the queue (including new microtasks generated during the execution of microtasks)
    • If there are no microtasks, check the macrotask queue and execute the first macrotask. After the macrotask is executed, check the microtask queue and repeat the above operations until the macrotask queue is empty.
    • Macro tasks (script, timer, ajax, I/O); micro tasks (promise.then, async await, MutationObserve to monitor DOM changes)

8. What is the js prototype chain?

        Every object in JavaScript has a prototype, which is the object from which they inherit properties and methods. And this prototype can have its own prototype, forming the so-called "prototype chain".
        When we access a property or method of a JavaScript object, we first look for the existence of the property or method in the object itself. If it doesn't exist, it searches up the object's prototype chain until it reaches Object.prototype. If it has not been found, undefined is returned.

        Therefore, through the prototype chain, we can achieve inheritance and code reuse. For example, we can create a base object and use it as a prototype for other objects so that they can share the base object's properties and methods.

9. Anti-shake & throttling

// 防抖-多次点击,只执行一次
function debounces(fn, time) {
	let timer
	
	return function() {
		if(timer) {
			clearTimeout(timer)
		}

		timer = setTimeout(() => {
			fn.apply(this, arguments);  
		}, time)
	}
}

// 节流-一定时间内,只执行一次
function throttle(fn, time) {
	let timer
	return function() {
		if (timer) {
			timer = setTimeout(() => {
				fn.apply(this, arguments)
				timer  = null
			}, time)
		}
	}
}

Let’s stop here today and keep updating...

Guess you like

Origin blog.csdn.net/qq_23334071/article/details/132832860