以下是一些常见的手写方法及其实现:
数组去重
1.使用set
const array = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = [...new Set(array)];
console.log(uniqueArray); // 输出: [1, 2, 3, 4, 5]
2.不使用set,暂列举一种
const array = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = [];
array.forEach(item => {
if (!uniqueArray.includes(item)) {
uniqueArray.push(item);
}
});
console.log(uniqueArray); // 输出: [1, 2, 3, 4, 5]
Promise
class MyPromise {
constructor(executor) {
this.state = "pending";
this.value = undefined;
this.onFulfilledCallbacks = [];
this.onRejectedCallbacks = [];
const resolve = (value) => {
if (this.state === "pending") {
this.state = "fulfilled";
this.value = value;
this.onFulfilledCallbacks.forEach((fn) => fn());
}
};
const reject = (reason) => {
if (this.state === "pending") {
this.state = "rejected";
this.value = reason;
this.onRejectedCallbacks.forEach((fn) => fn());
}
};
try {
executor(resolve, reject);
} catch (err) {
reject(err);
}
}
then(onFulfilled, onRejected) {
return new MyPromise((resolve, reject) => {
if (this.state === "fulfilled") {
try {
const result = onFulfilled(this.value);
resolve(result);
} catch (err) {
reject(err);
}
} else if (this.state === "rejected") {
try {
const result = onRejected(this.value);
resolve(result);
} catch (err) {
reject(err);
}
} else {
this.onFulfilledCallbacks.push(() => {
try {
const result = onFulfilled(this.value);
resolve(result);
} catch (err) {
reject(err);
}
});
this.onRejectedCallbacks.push(() => {
try {
const result = onRejected(this.value);
resolve(result);
} catch (err) {
reject(err);
}
});
}
});
}
}
debounce(防抖)
function debounce(fn, delay) {
let timer = null;
return function (...args) {
if (timer) clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(this, args);
}, delay);
};
}
throttle(节流)
function throttle(fn, delay) {
let lastTime = 0;
return function (...args) {
const now = Date.now();
if (now - lastTime >= delay) {
fn.apply(this, args);
lastTime = now;
}
};
}
deepClone(深拷贝)
function deepClone(obj, map = new WeakMap()) {
if (typeof obj !== "object" || obj === null) return obj;
if (map.has(obj)) return map.get(obj);
const result = Array.isArray(obj) ? [] : {};
map.set(obj, result);
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
result[key] = deepClone(obj[key], map);
}
}
return result;
}
flat(数组扁平化)
function flat(arr, depth = 1) {
return depth > 0
? arr.reduce(
(acc, val) =>
acc.concat(Array.isArray(val) ? flat(val, depth - 1) : val),
[]
)
: arr.slice();
}
执行一次函数(once)
function once(fn) {
let called = false; // 标记函数是否已被调用
let result; // 存储第一次调用的结果
return function (...args) {
if (!called) {
called = true; // 标记为已调用
result = fn.apply(this, args); // 调用原函数并存储结果
}
return result; // 返回第一次调用的结果
};
}
620

被折叠的 条评论
为什么被折叠?



