32个手撕JS,彻底摆脱初级前端(面试高频)-上篇

开发
作为前端开发,JS是重中之重,最近结束了面试的高峰期,基本上offer也定下来了就等开奖,趁着这个时间总结下32个手撕JS问题,这些都是高频面试题,完全理解之后定能彻底摆脱初级前端。

[[344056]]

 关于源码都紧遵规范,都可跑通MDN示例,其余的大多会涉及一些关于JS的应用题和本人面试过程

01.数组扁平化
数组扁平化是指将一个多维数组变为一个一维数组

  1. const arr = [1, [2, [3, [4, 5]]], 6]; 
  2. // => [1, 2, 3, 4, 5, 6] 
  3. 复制代码 

方法一:使用flat()

  1. const res1 = arr.flat(Infinity); 
  2. 复制代码 

方法二:利用正则

  1. const res2 = JSON.stringify(arr).replace(/\[|\]/g, '').split(','); 
  2. 复制代码 

但数据类型都会变为字符串

方法三:正则改良版本

  1. const res3 = JSON.parse('[' + JSON.stringify(arr).replace(/\[|\]/g, '') + ']'); 
  2. 复制代码 

方法四:使用reduce

  1. const flatten = arr => { 
  2.   return arr.reduce((pre, cur) => { 
  3.     return pre.concat(Array.isArray(cur) ? flatten(cur) : cur); 
  4.   }, []) 
  5. const res4 = flatten(arr); 
  6. 复制代码 

方法五:函数递归

  1. const res5 = []; 
  2. const fn = arr => { 
  3.   for (let i = 0; i < arr.length; i++) { 
  4.     if (Array.isArray(arr[i])) { 
  5.       fn(arr[i]); 
  6.     } else { 
  7.       res5.push(arr[i]); 
  8.     } 
  9.   } 
  10. fn(arr); 
  11. 复制代码 

02.数组去重

  1. const arr = [1, 1, '1', 17, truetruefalsefalse'true''a', {}, {}]; 
  2. // => [1, '1', 17, truefalse'true''a', {}, {}] 
  3. 复制代码 

方法一:利用Set

  1. const res1 = Array.from(new Set(arr)); 
  2. 复制代码 

方法二:两层for循环+splice

  1. const unique1 = arr => { 
  2.   let len = arr.length; 
  3.   for (let i = 0; i < len; i++) { 
  4.     for (let j = i + 1; j < len; j++) { 
  5.       if (arr[i] === arr[j]) { 
  6.         arr.splice(j, 1); 
  7.         // 每删除一个树,j--保证j的值经过自加后不变。同时,len--,减少循环次数提升性能 
  8.         len--; 
  9.         j--; 
  10.       } 
  11.     } 
  12.   } 
  13.   return arr; 
  14. 复制代码 

方法三:利用indexOf

  1. const unique2 = arr => { 
  2.   const res = []; 
  3.   for (let i = 0; i < arr.length; i++) { 
  4.     if (res.indexOf(arr[i]) === -1) res.push(arr[i]); 
  5.   } 
  6.   return res; 
  7. 复制代码 

当然也可以用include、filter,思路大同小异。

方法四:利用include

  1. const unique3 = arr => { 
  2.   const res = []; 
  3.   for (let i = 0; i < arr.length; i++) { 
  4.     if (!res.includes(arr[i])) res.push(arr[i]); 
  5.   } 
  6.   return res; 
  7. 复制代码 

方法五:利用filter

  1. const unique4 = arr => { 
  2.   return arr.filter((item, index) => { 
  3.     return arr.indexOf(item) === index
  4.   }); 
  5. 复制代码 

方法六:利用Map

  1. const unique5 = arr => { 
  2.   const map = new Map(); 
  3.   const res = []; 
  4.   for (let i = 0; i < arr.length; i++) { 
  5.     if (!map.has(arr[i])) { 
  6.       map.set(arr[i], true
  7.       res.push(arr[i]); 
  8.     } 
  9.   } 
  10.   return res; 
  11. 复制代码 

03.类数组转化为数组
类数组是具有length属性,但不具有数组原型上的方法。常见的类数组有arguments、DOM操作方法返回的结果。

方法一:Array.from

  1. Array.from(document.querySelectorAll('div')) 
  2. 复制代码 

方法二:Array.prototype.slice.call()

  1. Array.prototype.slice.call(document.querySelectorAll('div')) 
  2. 复制代码 

方法三:扩展运算符

  1. [...document.querySelectorAll('div')] 
  2. 复制代码 

方法四:利用concat

  1. Array.prototype.concat.apply([], document.querySelectorAll('div')); 
  2. 复制代码 

04.Array.prototype.filter()

  1. rray.prototype.filter = function(callback, thisArg) { 
  2.   if (this == undefined) { 
  3.     throw new TypeError('this is null or not undefined'); 
  4.   } 
  5.   if (typeof callback !== 'function') { 
  6.     throw new TypeError(callback + 'is not a function'); 
  7.   } 
  8.   const res = []; 
  9.   // 让O成为回调函数的对象传递(强制转换对象) 
  10.   const O = Object(this); 
  11.   // >>>0 保证len为number,且为正整数 
  12.   const len = O.length >>> 0; 
  13.   for (let i = 0; i < len; i++) { 
  14.     // 检查i是否在O的属性(会检查原型链) 
  15.     if (i in O) { 
  16.       // 回调函数调用传参 
  17.       if (callback.call(thisArg, O[i], i, O)) { 
  18.         res.push(O[i]); 
  19.       } 
  20.     } 
  21.   } 
  22.   return res; 
  23. 复制代码 

对于>>>0有疑问的:解释>>>0的作用

05.Array.prototype.map()

  1. Array.prototype.map = function(callback, thisArg) { 
  2.   if (this == undefined) { 
  3.     throw new TypeError('this is null or not defined'); 
  4.   } 
  5.   if (typeof callback !== 'function') { 
  6.     throw new TypeError(callback + ' is not a function'); 
  7.   } 
  8.   const res = []; 
  9.   // 同理 
  10.   const O = Object(this); 
  11.   const len = O.length >>> 0; 
  12.   for (let i = 0; i < len; i++) { 
  13.     if (i in O) { 
  14.       // 调用回调函数并传入新数组 
  15.       res[i] = callback.call(thisArg, O[i], i, this); 
  16.     } 
  17.   } 
  18.   return res; 
  19. 复制代码 

06.Array.prototype.forEach()

forEach跟map类似,唯一不同的是forEach是没有返回值的。

  1. Array.prototype.forEach = function(callback, thisArg) { 
  2.   if (this == null) { 
  3.     throw new TypeError('this is null or not defined'); 
  4.   } 
  5.   if (typeof callback !== "function") { 
  6.     throw new TypeError(callback + ' is not a function'); 
  7.   } 
  8.   const O = Object(this); 
  9.   const len = O.length >>> 0; 
  10.   let k = 0; 
  11.   while (k < len) { 
  12.     if (k in O) { 
  13.       callback.call(thisArg, O[k], k, O); 
  14.     } 
  15.     k++; 
  16.   } 
  17. 复制代码 

07.Array.prototype.reduce()

  1. Array.prototype.reduce = function(callback, initialValue) { 
  2.   if (this == undefined) { 
  3.     throw new TypeError('this is null or not defined'); 
  4.   } 
  5.   if (typeof callback !== 'function') { 
  6.     throw new TypeError(callbackfn + ' is not a function'); 
  7.   } 
  8.   const O = Object(this); 
  9.   const len = this.length >>> 0; 
  10.   let accumulator = initialValue; 
  11.   let k = 0; 
  12.   // 如果第二个参数为undefined的情况下 
  13.   // 则数组的第一个有效值作为累加器的初始值 
  14.   if (accumulator === undefined) { 
  15.     while (k < len && !(k in O)) { 
  16.       k++; 
  17.     } 
  18.     // 如果超出数组界限还没有找到累加器的初始值,则TypeError 
  19.     if (k >= len) { 
  20.       throw new TypeError('Reduce of empty array with no initial value'); 
  21.     } 
  22.     accumulator = O[k++]; 
  23.   } 
  24.   while (k < len) { 
  25.     if (k in O) { 
  26.       accumulator = callback.call(undefined, accumulator, O[k], k, O); 
  27.     } 
  28.     k++; 
  29.   } 
  30.   return accumulator; 
  31. 复制代码 

08.Function.prototype.apply()
第一个参数是绑定的this,默认为window,第二个参数是数组或类数组

  1. Function.prototype.apply = function(context = window, args) { 
  2.   if (typeof this !== 'function') { 
  3.     throw new TypeError('Type Error'); 
  4.   } 
  5.   const fn = Symbol('fn'); 
  6.   context[fn] = this; 
  7.  
  8.   const res = context[fn](...args); 
  9.   delete context[fn]; 
  10.   return res; 
  11. 复制代码 

09.Function.prototype.call
于call唯一不同的是,call()方法接受的是一个参数列表

  1. Function.prototype.call = function(context = window, ...args) { 
  2.   if (typeof this !== 'function') { 
  3.     throw new TypeError('Type Error'); 
  4.   } 
  5.   const fn = Symbol('fn'); 
  6.   context[fn] = this; 
  7.  
  8.   const res = this[fn](...args); 
  9.   delete this.fn; 
  10.   return res; 
  11. 复制代码 

10.Function.prototype.bind

  1. Function.prototype.bind = function(context, ...args) { 
  2.   if (typeof this !== 'function') { 
  3.     throw new Error("Type Error"); 
  4.   } 
  5.   // 保存this的值 
  6.   var self = this; 
  7.  
  8.   return function F() { 
  9.     // 考虑new的情况 
  10.     if(this instanceof F) { 
  11.       return new self(...args, ...arguments) 
  12.     } 
  13.     return self.apply(context, [...args, ...arguments]) 
  14.   } 
  15. 复制代码 

11.debounce(防抖)
触发高频时间后n秒内函数只会执行一次,如果n秒内高频时间再次触发,则重新计算时间。

  1. const debounce = (fn, time) => { 
  2.   let timeout = null
  3.   return function() { 
  4.     clearTimeout(timeout) 
  5.     timeout = setTimeout(() => { 
  6.       fn.apply(this, arguments); 
  7.     }, time); 
  8.   } 
  9. }; 
  10. 复制代码 

防抖常应用于用户进行搜索输入节约请求资源,window触发resize事件时进行防抖只触发一次。

12.throttle(节流)
高频时间触发,但n秒内只会执行一次,所以节流会稀释函数的执行频率。

  1. const throttle = (fn, time) => { 
  2.   let flag = true
  3.   return function() { 
  4.     if (!flag) return
  5.     flag = false
  6.     setTimeout(() => { 
  7.       fn.apply(this, arguments); 
  8.       flag = true
  9.     }, time); 
  10.   } 
  11. 复制代码 

节流常应用于鼠标不断点击触发、监听滚动事件。

13.函数珂里化

  1. 指的是将一个接受多个参数的函数 变为 接受一个参数返回一个函数的固定形式,这样便于再次调用,例如f(1)(2) 

经典面试题:实现add(1)(2)(3)(4)=10; 、 add(1)(1,2,3)(2)=9;

  1. function add() { 
  2.   const _args = [...arguments]; 
  3.   function fn() { 
  4.     _args.push(...arguments); 
  5.     return fn; 
  6.   } 
  7.   fn.toString = function() { 
  8.     return _args.reduce((sum, cur) => sum + cur); 
  9.   } 
  10.   return fn; 
  11. 复制代码 

14.模拟new操作
3个步骤:

  1. 以ctor.prototype为原型创建一个对象。
  2. 执行构造函数并将this绑定到新创建的对象上。
  3. 判断构造函数执行返回的结果是否是引用数据类型,若是则返回构造函数执行的结果,否则返回创建的对象。
  1. function newOperator(ctor, ...args) { 
  2.   if (typeof ctor !== 'function') { 
  3.     throw new TypeError('Type Error'); 
  4.   } 
  5.   const obj = Object.create(ctor.prototype); 
  6.   const res = ctor.apply(obj, args); 
  7.  
  8.   const isObject = typeof res === 'object' && res !== null
  9.   const isFunction = typeof res === 'function'
  10.   return isObject || isFunction ? res : obj; 
  11. 复制代码 

15.instanceof
instanceof运算符用于检测构造函数的prototype属性是否出现在某个实例对象的原型链上。

  1. const myInstanceof = (leftright) => { 
  2.   // 基本数据类型都返回false 
  3.   if (typeof left !== 'object' || left === nullreturn false
  4.   let proto = Object.getPrototypeOf(left); 
  5.   while (true) { 
  6.     if (proto === nullreturn false
  7.     if (proto === right.prototype) return true
  8.     proto = Object.getPrototypeOf(proto); 
  9.   } 
  10. 复制代码 

16.原型继承
这里只写寄生组合继承了,中间还有几个演变过来的继承但都有一些缺陷

  1. function Parent() { 
  2.   this.name = 'parent'
  3. function Child() { 
  4.   Parent.call(this); 
  5.   this.type = 'children'
  6. Child.prototype = Object.create(Parent.prototype); 
  7. Child.prototype.constructor = Child; 
  8. 复制代码 

 

 

责任编辑:姜华 来源: 前端UpUp
相关推荐

2021-06-09 07:01:30

前端CallApply

2021-07-15 14:29:06

LRU算法

2021-09-06 08:13:35

APM系统监控

2021-05-18 07:52:31

PromiseAsyncAwait

2020-09-17 14:04:32

拷贝

2020-09-15 08:55:07

算法数据基础

2023-06-25 08:38:09

多线程循环打印

2023-08-02 08:54:58

Java弱引用链表

2021-10-31 07:38:37

排序算法代码

2023-09-18 09:10:11

Golang高性能缓存库

2020-09-16 14:17:42

flat方法

2019-11-26 10:30:11

CSS前端面试题

2015-08-21 10:38:16

编程语言GoC语言

2022-04-15 09:23:29

Kubernetes面试题

2021-02-23 12:43:39

Redis面试题缓存

2015-11-06 11:02:24

微信罗素生活

2015-08-06 15:25:44

prototypeconstructorjs

2020-04-10 08:22:45

CSS语言层叠样式表

2019-12-26 09:52:33

Redis集群线程

2024-01-03 13:39:00

JS,Javascrip算法
点赞
收藏

51CTO技术栈公众号