前端面试常见手写题整理

妖狐艹你老母 2022-12-15 12:59 276阅读 0赞

前端面试手写题

整理前端面试常见的手写题,面试出现概率极高,建议每个都过自己过一遍,加深印象。

你可以 watch 一下这个 GitHub 仓库,会持续收集、整理和维护。

在这里插入图片描述

实现 bind()

  1. Function.prototype.MyBind = function (context, ...args) {
  2. let self = this;
  3. return function() {
  4. return self.apply(context, args);
  5. }
  6. }
  7. // test
  8. let a = { name: 'jack'}
  9. let test = function() {
  10. console.log(this.name); // jack
  11. }
  12. let rs = test.MyBind(a);
  13. rs();

实现 apply()

  1. Function.prototype.myApply = function (context, args) {
  2. context.fn = this;
  3. let res;
  4. if (!args){
  5. res = context.fn();
  6. } else {
  7. res = context.fn(...args)
  8. }
  9. return res;
  10. }
  11. // test
  12. let obj = {
  13. name: 'jack'
  14. }
  15. function test(arg1, arg2, arg3) {
  16. console.log(this.name) // jack
  17. console.log(arg1, arg2, arg3); // 1 2 3
  18. }
  19. test.myApply(obj, [1,2,3]);

实现 call()

  1. Function.prototype.myCall = function (context, ...rest) {
  2. context.fn = this;
  3. var result = context.fn(...rest);
  4. delete context.fn;
  5. return result;
  6. }
  7. // test
  8. let obj = {
  9. name: 'jack'
  10. }
  11. function test(arg1, arg2, arg3) {
  12. console.log(this.name) // jack
  13. console.log(arg1, arg2, arg3); // 1 2 3
  14. }
  15. test.myCall(obj, 1,2,3);

实现 instanceof

  1. function myInstanceOf(left, right) {
  2. let prototype = right.prototype;
  3. left = left.__proto__;
  4. while(true) {
  5. if (!left) return false;
  6. if (left == prototype) return true;
  7. left = left.__proto__;
  8. }
  9. }
  10. console.log(myInstanceOf([], Array)); // true

实现 new

  1. function myNew (fun, ...args) {
  2. let obj = { };
  3. obj.__proto__ = fun.prototype;
  4. let res = fun.apply(obj, args);
  5. return res instanceof Object ? res : obj;
  6. }
  7. function Animal(name) {
  8. this.name = name;
  9. }
  10. let animal = myNew(Animal, 'dog');
  11. console.log(animal.name) // dog

实现 jsonp

  1. var newscript = document.createElement('script');
  2. newscript.src = 'https://www.adb.com?callback=fn'
  3. document.body.appendChild(newscript);
  4. function fn(data) {
  5. console.log(data);
  6. }

实现 Promise

  1. const PENDING = Symbol();
  2. const REJECTED = Symbol();
  3. const FULLFILLED = Symbol();
  4. const MyPromise = function(fn) {
  5. this.state = PENDING;
  6. this.value = '';
  7. const resolve = (value) => {
  8. this.state = FULLFILLED;
  9. this.value = value;
  10. }
  11. const reject = (error) => {
  12. this.state = REJECTED;
  13. this.value = error;
  14. }
  15. this.then = (onFullFill, onReject) => {
  16. if (this.state == FULLFILLED) {
  17. onFullFill(this.value);
  18. } else {
  19. onReject(this.value);
  20. }
  21. }
  22. try {
  23. fn(resolve, reject);
  24. } catch(error) {
  25. reject(error);
  26. }
  27. }
  28. // test
  29. let p = new MyPromise((resolve, reject) => {
  30. resolve('hello');
  31. })
  32. p.then(res => {
  33. console.log(res); // hello
  34. })

实现 Promise.all()

  1. function isPromise(obj) {
  2. return !!obj && (typeof obj === 'function' || typeof obj === 'object') && typeof obj.then == 'function';
  3. }
  4. function myPromiseAll(arr) {
  5. let res = []
  6. return new Promise((resolve, reject) => {
  7. for (let i = 0; i < arr.length; i++) {
  8. if (isPromise(arr[i])) {
  9. arr[i].then(data => {
  10. res[i] = data;
  11. if (res.length === arr.length) {
  12. resolve(res)
  13. }
  14. }).catch(error => {
  15. reject(error)
  16. })
  17. } else {
  18. res[i] = arr[i];
  19. }
  20. }
  21. })
  22. }

实现 Promise.race()

  1. function myPromiseRace(arr) {
  2. return new Promise((resolve, reject) => {
  3. for (let i = 0; i < arr.length; i++) {
  4. return arr[i].then(resolve, reject)
  5. }
  6. })
  7. }

实现 EventEmitter 订阅监听模式

  1. class EventEmitter {
  2. constructor() {
  3. this.events = { };
  4. }
  5. on (eventName, callback) {
  6. if(!this.events[eventName]) {
  7. this.events[eventName] = [callback];
  8. } else {
  9. this.events[eventName].push(callback);
  10. }
  11. }
  12. emit(eventName, ...args) {
  13. this.events[eventName].forEach(fn => fn.apply(this, args));
  14. }
  15. once(eventName, callback) {
  16. const fn = () => {
  17. callback();
  18. this.remove(eventName, fn);
  19. }
  20. this.on(eventName, fn)
  21. }
  22. remove(eventName, callback) {
  23. this.events[eventName] = this.events[eventName].filter(fn => fn != callback);
  24. }
  25. }

setTimout 实现 setInterval

  1. function myInterval(fn, time) {
  2. let context = this;
  3. setTimeout(() => {
  4. fn.call(context);
  5. myInterval(fn, time);
  6. }, time);
  7. }

深拷贝

  1. function deepClone(obj) {
  2. // 先判断是对象还是数组
  3. let copy = obj instanceof Array ? [] : { };
  4. for (let key in obj) {
  5. // 判断是否是对象上的属性,而不是原型上的属性
  6. if (obj.hasOwnProperty(key)) {
  7. // obj[key] 是否是对象,如果是对象,递归遍历
  8. copy[key] = typeof obj[key] === 'object' ? deepClone(obj[key]) : obj[key];
  9. }
  10. }
  11. return copy;
  12. }
  13. // test
  14. console.log(deepClone({ name: 'jack', birth: { year: '1997', month: '10'}})) // {name: 'jack', birth: {…}}

数组拍平

  1. var flatten = function(arr) {
  2. let res = [];
  3. for (let i = 0; i < arr.length; i++) {
  4. if (Array.isArray(arr[i])) {
  5. res = res.concat(flatten(arr[i]))
  6. } else {
  7. res.push(arr[i])
  8. }
  9. }
  10. return res;
  11. }
  12. console.log(flatten([1,[1,2,[2,4]],3,5])); // [1, 1, 2, 2, 4, 3, 5]

函数防抖

  1. function debounce(fn, wait) {
  2. let timeout = null;
  3. return function() {
  4. let context = this;
  5. let args = arguments;
  6. if (timeout) clearTimeout(timeout);
  7. timeout = setTimeout(() => {
  8. fn.apply(context, args);
  9. }, wait);
  10. }
  11. }

函数节流

  1. function throttle(fn, wait) {
  2. let pre = new Date();
  3. return function() {
  4. let context = this;
  5. let args = arguments;
  6. let now = new Date();
  7. if (now - pre >= wait) {
  8. fn.apply(context, args);
  9. pre = now;
  10. }
  11. }
  12. }

函数柯里化(实现 sum(1,2)(3)())

  1. function sum(...args1) {
  2. let x = args1.reduce((prev, next) => { return prev+next;})
  3. return function(...args2) {
  4. if (args2.length == 0) return x;
  5. let y = args2.reduce((prev, next) => { return prev+next;})
  6. return sum(x+y)
  7. }
  8. }
  9. console.log(sum(1,2,2,5)(7)()) // 17

快速排序

  1. function quicksort(arr) {
  2. if (arr.length <= 1) return arr;
  3. let pivotIndex = arr.length >> 1;
  4. let pivot = arr.splice(pivotIndex, 1)[0];
  5. let left = [];
  6. let right = [];
  7. for (let i = 0; i < arr.length; i++) {
  8. if (arr[i] <= pivot) {
  9. left.push(arr[i]);
  10. } else {
  11. right.push(arr[i]);
  12. }
  13. }
  14. return quicksort(left).concat(pivot, quicksort(right));
  15. }
  16. console.log(quicksort([4,3,5,2,1,6])); // [1, 2, 3, 4, 5, 6]

归并排序

  1. function merge(left, right) {
  2. let res = [];
  3. while(left.length > 0 && right.length > 0) {
  4. if (left[0] < right[0]) {
  5. res.push(left.shift());
  6. } else {
  7. res.push(right.shift());
  8. }
  9. }
  10. return res.concat(left).concat(right);
  11. }
  12. function mergeSort(arr) {
  13. if (arr.length == 1) return arr;
  14. var middle = Math.floor(arr.length / 2);
  15. var left = arr.slice(0, middle);
  16. var right = arr.slice(middle);
  17. return merge(mergeSort(left), mergeSort(right));
  18. }
  19. console.log(mergeSort([3,2,4,5,1,6])); // [1, 2, 3, 4, 5, 6]

发表评论

表情:
评论列表 (有 0 条评论,276人围观)

还没有评论,来说两句吧...

相关阅读