本文主要是介绍前端面试手撕题收集(自用),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
对象深拷贝
function deepClone(source, clonedMap = new Map()) {if (typeof source !== object || source === null) {return source; // 如果是基本类型,直接返回值,不需要深拷贝}// 如果这个对象已经被拷贝过,则直接跳过if (cloneMap.has(source)) {return cloneMap.get(source);} const target = Array.isArray(source) ? [] : {};clonedMap.set(source, target);for (const key in source) {if (typeof source[key] === object && source !== null ){target[key] = deepClone(source[key], clonedMap);} else {target[key] = source[key];}}return target;
}
Promise
Promise.all
function all(promises) {return new Promise((resolve, reject) => {let resolvedCount = 0; // 统计有多少个promise达到resolvedlet results = new Array(promises.length);promises.forEach((promise, index) => {// 如果promise执行成功,将resolve的值存储到resule中,如果失败,直接进catchPromise.resolve(promise).then((value) => {resolvedCount++;results[index] = value;if (resolvedCount == promises.length) {resolve(results); // new Promise对象时带的参数}}).catch((error) => {reject(error);})})})
}
promise.race
function race(promises) {return newPromise((resolve, reject) => {// 遍历所有promise。最先执行结束的promise决定了Promise.race的结果promises.forEach((promise) => {Promise.resolve(promise).then((value) => {resolve(value);}).catch((error)=>{reject(error);})})})
}
数组扁平化
Array.prototype.customFlatten = function() { let flat = [];for (let item of this) {if (Array.isArray(item)) {flat = flat.concat(item.customFlatten());} else {flat.push(item);}}return flat;
}
函数柯里化
function curry(fn) {return function curried(...args) {if (args.length >= fn.length) { // 参数个数达到length,执行原函数return fn.apply(this, args);} else { // 如果参数没有达到length,返回新的函数return function (...args2) {return curried.apply(this, args.concat(args2));}}}
}
手写call
Function.prototype._call = function(obj, ...params) {const key = Symbol('key');obj[key] = this;const res = obj[key](...params);delete obj[key]return res;
}
手写bind
Function.prototype._bind = function(target, ...arguments1) {return (...arguments2) => {return this.call(target, ...arguments1, ...arguments2);}
}
这篇关于前端面试手撕题收集(自用)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!