new
function myNew(constructor, ...args) {
if (typeof constructor !== 'function') {
throw new TypeError('Constructor must be a function');
}
const newObj = Object.create(constructor.prototype);
const result = constructor.apply(newObj, args);
return result && (typeof result === 'object' || typeof result === 'function')
? result
: newObj;
}
防抖
function debounce(func, wait) {
let timeout; return function (...args) {
const context = this;
if (timeout) clearTimeout(timeout);
timeout = setTimeout(() => {
func.apply(context, args);
}, wait);
};
}
function performSearch(query) {
console.log('Searching for:', query);
}
const debouncedSearch = debounce(performSearch, 300);
debouncedSearch('apple');
debouncedSearch('banana');
debouncedSearch('cherry');
节流
function throttle(func, limit) {
let lastFunc;
let lastRan;
return function (...args) {
const context = this;
const now = Date.now();
if (!lastRan) {
func.apply(context, args);
lastRan = now;
} else {
clearTimeout(lastFunc);
lastFunc = setTimeout(() => {
func.apply(context, args);
lastRan = now;
}, Math.max(limit - (now - lastRan), 0));
}
};
}
const handleScroll = throttle(() => {
console.log('Scroll event handler called');
}, 1000);
window.addEventListener('scroll', handleScroll);
冒泡
function bubbleSort(arr) {
let n = arr.length;
let swapped;
for (let i = 0; i < n - 1; i++) {
swapped = false;
for (let j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
swapped = true;
}
}
if (!swapped) break;
}
return arr;
}
const array = [64, 34, 25, 12, 22, 11, 90];
console.log('原始数组:', array);
const sortedArray = bubbleSort(array);
console.log('排序后的数组:', sortedArray);
选择排序
function selectionSort(arr) {
let n = arr.length;
for (let i = 0; i < n - 1; i++) {
let minIndex = i;
for (let j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
if (minIndex !== i) {
[arr[i], arr[minIndex]] = [arr[minIndex], arr[i]];
}
}
return arr;
}
const array = [64, 25, 12, 22, 11];
console.log('Original array:', array);
console.log('Sorted array:', selectionSort(array));
实现promise.all()
function customPromiseAll(promises) {
return new Promise((resolve, reject) => {
const results = [];
let completedCount = 0;
if (!Array.isArray(promises)) {
return reject(new TypeError('Argument must be an array'));
}
if (promises.length === 0) {
return resolve(results);
}
promises.forEach((promise, index) => {
Promise.resolve(promise)
.then(value => {
results[index] = value;
completedCount++;
if (completedCount === promises.length) {
resolve(results);
}
})
.catch(error => {
reject(error);
});
});
});
}
const p1 = Promise.resolve(1);
const p2 = Promise.resolve(2);
const p3 = new Promise((resolve, reject) => setTimeout(() => resolve(3), 1000));
customPromiseAll([p1, p2, p3])
.then(results => {
console.log(results);
})
.catch(error => {
console.error(error);
});
树结构转换
function translateToTree(arr) {
const map = new Map();
const result = [];
arr.forEach((item) => {
map.set(item.id, { ...item });
});
arr.forEach((item) => {
const node = map.get(item.id);
const parent = map.get(item.pid);
if (parent) {
if (!parent.children) {
parent.children = [];
}
parent.children.push(node);
} else {
result.push(node);
}
});
return result;
}
const source = [
{ id: 1, pid: 0, name: 'body' },
{ id: 2, pid: 1, name: 'title' },
{ id: 3, pid: 2, name: 'div' }
];
实现深复制
function deepClone(value, map = new WeakMap()) {
if (value === null || typeof value !== 'object') {
return value;
}
if (value instanceof Date) {
return new Date(value.getTime());
}
if (value instanceof RegExp) {
return new RegExp(value);
}
if (map.has(value)) {
return map.get(value);
}
const copy = Array.isArray(value) ? [] : {};
map.set(value, copy);
Object.keys(value).forEach(key => {
copy[key] = deepClone(value[key], map);
});
return copy;
}
判断是否循环引用
function isCycleObject(obj) {
const set = new WeakSet();
function func(current) {
if (current === null || typeof current !== "object") {
return false;
}
if (set.has(current)) {
return true;
}
set.add(current);
for (const key of Object.keys(current)) {
if (func(current[key])) {
return true;
}
}
return false;
}
return func(obj);
}
const objA = {};
const objB = { a: objA };
objA.b = objB;
console.log(hasCircularReference(objA));
const objC = { name: 'Alice' };
console.log(hasCircularReference(objC));
转换千分位
function formatWithCommas(numberStr) {
if (isNaN(numberStr) || numberStr.trim() === '') {
throw new Error("输入的字符串不是有效的数字");
}
const [integerPart, decimalPart] = numberStr.split('.');
let result = '';
let count = 0;
for (let i = integerPart.length - 1; i >= 0; i--) {
result = integerPart[i] + result;
count++;
if (count % 3 === 0 && i > 0) {
result = ',' + result;
}
}
return decimalPart ? `${result}.${decimalPart}` : result;
}
try {
const formattedStr = formatWithCommas("1234567890.12");
console.log(formattedStr);
} catch (error) {
console.error(error.message);
}
统计数组中元素出现次数
function countOccurrences(array) {
const counts = {};
for (const item of array) {
counts[item] = (counts[item] || 0) + 1;
}
return counts;
}
const array = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple'];
console.log(countOccurrences(array));
实现flat
function newFlat(arr, n) {
let result = [];
arr.forEach((item) => {
if (Array.isArray(item) && n > 0) {
result = result.concat(newFlat(item), n - 1);
} else {
result.push(item);
}
});
return result;
}
实现字符串中不重复的最大长度
var lengthOfLongestSubstring = function (s) {
let map = new Map();
let i = -1;
let res = 0;
let n = s.length;
for (let j = 0; j < n; j++) {
if (map.has(s[j])) {
i = Math.max(i, map.get(s[j]));
}
res = Math.max(res, j - i);
map.set(s[j], j);
}
return res;
};