详细整理出2023前端面试常考的手写题
时间: 2023-06-13 19:05:26 浏览: 160
以下是一些可能会在2023前端面试中常见的手写题:
1. 实现一个事件订阅/发布模式
```javascript
class EventEmitter {
constructor() {
this.events = {};
}
on(eventName, callback) {
if (!this.events[eventName]) {
this.events[eventName] = [];
}
this.events[eventName].push(callback);
}
emit(eventName, ...args) {
const callbacks = this.events[eventName];
if (callbacks) {
callbacks.forEach((callback) => {
callback(...args);
});
}
}
off(eventName, callback) {
const callbacks = this.events[eventName];
if (callbacks) {
const index = callbacks.indexOf(callback);
if (index !== -1) {
callbacks.splice(index, 1);
}
}
}
}
```
2. 实现一个 Promise
```javascript
class MyPromise {
constructor(executor) {
this.state = "pending";
this.value = undefined;
this.reason = undefined;
this.onFulfilledCallbacks = [];
this.onRejectedCallbacks = [];
const resolve = (value) => {
if (this.state === "pending") {
this.state = "fulfilled";
this.value = value;
this.onFulfilledCallbacks.forEach((callback) => callback());
}
};
const reject = (reason) => {
if (this.state === "pending") {
this.state = "rejected";
this.reason = reason;
this.onRejectedCallbacks.forEach((callback) => callback());
}
};
try {
executor(resolve, reject);
} catch (error) {
reject(error);
}
}
then(onFulfilled, onRejected) {
const promise2 = new MyPromise((resolve, reject) => {
const onFulfilledCallback = () => {
try {
const x = onFulfilled(this.value);
resolvePromise(promise2, x, resolve, reject);
} catch (error) {
reject(error);
}
};
const onRejectedCallback = () => {
try {
const x = onRejected(this.reason);
resolvePromise(promise2, x, resolve, reject);
} catch (error) {
reject(error);
}
};
if (this.state === "fulfilled") {
onFulfilledCallback();
} else if (this.state === "rejected") {
onRejectedCallback();
} else {
this.onFulfilledCallbacks.push(onFulfilledCallback);
this.onRejectedCallbacks.push(onRejectedCallback);
}
});
return promise2;
}
catch(onRejected) {
return this.then(null, onRejected);
}
}
function resolvePromise(promise, x, resolve, reject) {
if (promise === x) {
reject(new TypeError("Chaining cycle detected"));
} else if (x instanceof MyPromise) {
x.then(
(value) => resolve(value),
(reason) => reject(reason)
);
} else {
resolve(x);
}
}
```
3. 实现一个防抖函数
```javascript
function debounce(func, delay) {
let timer;
return function (...args) {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
func.apply(this, args);
}, delay);
};
}
```
4. 实现一个节流函数
```javascript
function throttle(func, delay) {
let timer;
return function (...args) {
if (!timer) {
timer = setTimeout(() => {
func.apply(this, args);
timer = null;
}, delay);
}
};
}
```
5. 实现一个深拷贝函数
```javascript
function deepClone(obj) {
if (typeof obj !== "object" || obj === null) {
return obj;
}
let result;
if (Array.isArray(obj)) {
result = [];
} else {
result = {};
}
for (let key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
result[key] = deepClone(obj[key]);
}
}
return result;
}
```
阅读全文