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

 关于源码都紧遵规范,都可跑通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. }
  6. const res4 = flatten(arr);
  7. 复制代码

方法五:函数递归

 
 
 
 
  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. }
  11. fn(arr);
  12. 复制代码

02.数组去重

 
 
 
 
  1. const arr = [1, 1, '1', 17, true, true, false, false, 'true', 'a', {}, {}];
  2. // => [1, '1', 17, true, false, '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. }
  15. 复制代码

方法三:利用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. }
  8. 复制代码

当然也可以用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. }
  8. 复制代码

方法五:利用filter

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

方法六:利用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. }
  12. 复制代码

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. }
  24. 复制代码

对于>>>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. }
  20. 复制代码

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. }
  18. 复制代码

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. }
  32. 复制代码

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.   const res = context[fn](...args);
  8.   delete context[fn];
  9.   return res;
  10. }
  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.   const res = this[fn](...args);
  8.   delete this.fn;
  9.   return res;
  10. }
  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.   return function F() {
  8.     // 考虑new的情况
  9.     if(this instanceof F) {
  10.       return new self(...args, ...arguments)
  11.     }
  12.     return self.apply(context, [...args, ...arguments])
  13.   }
  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. }
  12. 复制代码

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

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. }
  12. 复制代码

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.   const isObject = typeof res === 'object' && res !== null;
  8.   const isFunction = typeof res === 'function';
  9.   return isObject || isFunction ? res : obj;
  10. }
  11. 复制代码

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

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

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

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

文章题目:32个手撕JS,彻底摆脱初级前端(面试高频)-上篇
文章分享:http://www.shufengxianlan.com/qtweb/news45/366445.html

成都网站建设公司_创新互联,为您提供自适应网站做网站定制开发ChatGPT网站收录小程序开发

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联