32個手撕JS,徹底擺脫初級前端(面試高頻)-上篇
關于源碼都緊遵規范,都可跑通MDN示例,其余的大多會涉及一些關于JS的應用題和本人面試過程
01.數組扁平化
數組扁平化是指將一個多維數組變為一個一維數組
- const arr = [1, [2, [3, [4, 5]]], 6];
- // => [1, 2, 3, 4, 5, 6]
- 復制代碼
方法一:使用flat()
- const res1 = arr.flat(Infinity);
- 復制代碼
方法二:利用正則
- const res2 = JSON.stringify(arr).replace(/\[|\]/g, '').split(',');
- 復制代碼
但數據類型都會變為字符串
方法三:正則改良版本
- const res3 = JSON.parse('[' + JSON.stringify(arr).replace(/\[|\]/g, '') + ']');
- 復制代碼
方法四:使用reduce
- const flatten = arr => {
- return arr.reduce((pre, cur) => {
- return pre.concat(Array.isArray(cur) ? flatten(cur) : cur);
- }, [])
- }
- const res4 = flatten(arr);
- 復制代碼
方法五:函數遞歸
- const res5 = [];
- const fn = arr => {
- for (let i = 0; i < arr.length; i++) {
- if (Array.isArray(arr[i])) {
- fn(arr[i]);
- } else {
- res5.push(arr[i]);
- }
- }
- }
- fn(arr);
- 復制代碼
02.數組去重
- const arr = [1, 1, '1', 17, true, true, false, false, 'true', 'a', {}, {}];
- // => [1, '1', 17, true, false, 'true', 'a', {}, {}]
- 復制代碼
方法一:利用Set
- const res1 = Array.from(new Set(arr));
- 復制代碼
方法二:兩層for循環+splice
- const unique1 = arr => {
- let len = arr.length;
- for (let i = 0; i < len; i++) {
- for (let j = i + 1; j < len; j++) {
- if (arr[i] === arr[j]) {
- arr.splice(j, 1);
- // 每刪除一個樹,j--保證j的值經過自加后不變。同時,len--,減少循環次數提升性能
- len--;
- j--;
- }
- }
- }
- return arr;
- }
- 復制代碼
方法三:利用indexOf
- const unique2 = arr => {
- const res = [];
- for (let i = 0; i < arr.length; i++) {
- if (res.indexOf(arr[i]) === -1) res.push(arr[i]);
- }
- return res;
- }
- 復制代碼
當然也可以用include、filter,思路大同小異。
方法四:利用include
- const unique3 = arr => {
- const res = [];
- for (let i = 0; i < arr.length; i++) {
- if (!res.includes(arr[i])) res.push(arr[i]);
- }
- return res;
- }
- 復制代碼
方法五:利用filter
- const unique4 = arr => {
- return arr.filter((item, index) => {
- return arr.indexOf(item) === index;
- });
- }
- 復制代碼
方法六:利用Map
- const unique5 = arr => {
- const map = new Map();
- const res = [];
- for (let i = 0; i < arr.length; i++) {
- if (!map.has(arr[i])) {
- map.set(arr[i], true)
- res.push(arr[i]);
- }
- }
- return res;
- }
- 復制代碼
03.類數組轉化為數組
類數組是具有length屬性,但不具有數組原型上的方法。常見的類數組有arguments、DOM操作方法返回的結果。
方法一:Array.from
- Array.from(document.querySelectorAll('div'))
- 復制代碼
方法二:Array.prototype.slice.call()
- Array.prototype.slice.call(document.querySelectorAll('div'))
- 復制代碼
方法三:擴展運算符
- [...document.querySelectorAll('div')]
- 復制代碼
方法四:利用concat
- Array.prototype.concat.apply([], document.querySelectorAll('div'));
- 復制代碼
04.Array.prototype.filter()
- rray.prototype.filter = function(callback, thisArg) {
- if (this == undefined) {
- throw new TypeError('this is null or not undefined');
- }
- if (typeof callback !== 'function') {
- throw new TypeError(callback + 'is not a function');
- }
- const res = [];
- // 讓O成為回調函數的對象傳遞(強制轉換對象)
- const O = Object(this);
- // >>>0 保證len為number,且為正整數
- const len = O.length >>> 0;
- for (let i = 0; i < len; i++) {
- // 檢查i是否在O的屬性(會檢查原型鏈)
- if (i in O) {
- // 回調函數調用傳參
- if (callback.call(thisArg, O[i], i, O)) {
- res.push(O[i]);
- }
- }
- }
- return res;
- }
- 復制代碼
對于>>>0有疑問的:解釋>>>0的作用
05.Array.prototype.map()
- Array.prototype.map = function(callback, thisArg) {
- if (this == undefined) {
- throw new TypeError('this is null or not defined');
- }
- if (typeof callback !== 'function') {
- throw new TypeError(callback + ' is not a function');
- }
- const res = [];
- // 同理
- const O = Object(this);
- const len = O.length >>> 0;
- for (let i = 0; i < len; i++) {
- if (i in O) {
- // 調用回調函數并傳入新數組
- res[i] = callback.call(thisArg, O[i], i, this);
- }
- }
- return res;
- }
- 復制代碼
06.Array.prototype.forEach()
forEach跟map類似,唯一不同的是forEach是沒有返回值的。
- Array.prototype.forEach = function(callback, thisArg) {
- if (this == null) {
- throw new TypeError('this is null or not defined');
- }
- if (typeof callback !== "function") {
- throw new TypeError(callback + ' is not a function');
- }
- const O = Object(this);
- const len = O.length >>> 0;
- let k = 0;
- while (k < len) {
- if (k in O) {
- callback.call(thisArg, O[k], k, O);
- }
- k++;
- }
- }
- 復制代碼
07.Array.prototype.reduce()
- Array.prototype.reduce = function(callback, initialValue) {
- if (this == undefined) {
- throw new TypeError('this is null or not defined');
- }
- if (typeof callback !== 'function') {
- throw new TypeError(callbackfn + ' is not a function');
- }
- const O = Object(this);
- const len = this.length >>> 0;
- let accumulator = initialValue;
- let k = 0;
- // 如果第二個參數為undefined的情況下
- // 則數組的第一個有效值作為累加器的初始值
- if (accumulator === undefined) {
- while (k < len && !(k in O)) {
- k++;
- }
- // 如果超出數組界限還沒有找到累加器的初始值,則TypeError
- if (k >= len) {
- throw new TypeError('Reduce of empty array with no initial value');
- }
- accumulator = O[k++];
- }
- while (k < len) {
- if (k in O) {
- accumulator = callback.call(undefined, accumulator, O[k], k, O);
- }
- k++;
- }
- return accumulator;
- }
- 復制代碼
08.Function.prototype.apply()
第一個參數是綁定的this,默認為window,第二個參數是數組或類數組
- Function.prototype.apply = function(context = window, args) {
- if (typeof this !== 'function') {
- throw new TypeError('Type Error');
- }
- const fn = Symbol('fn');
- context[fn] = this;
- const res = context[fn](...args);
- delete context[fn];
- return res;
- }
- 復制代碼
09.Function.prototype.call
于call唯一不同的是,call()方法接受的是一個參數列表
- Function.prototype.call = function(context = window, ...args) {
- if (typeof this !== 'function') {
- throw new TypeError('Type Error');
- }
- const fn = Symbol('fn');
- context[fn] = this;
- const res = this[fn](...args);
- delete this.fn;
- return res;
- }
- 復制代碼
10.Function.prototype.bind
- Function.prototype.bind = function(context, ...args) {
- if (typeof this !== 'function') {
- throw new Error("Type Error");
- }
- // 保存this的值
- var self = this;
- return function F() {
- // 考慮new的情況
- if(this instanceof F) {
- return new self(...args, ...arguments)
- }
- return self.apply(context, [...args, ...arguments])
- }
- }
- 復制代碼
11.debounce(防抖)
觸發高頻時間后n秒內函數只會執行一次,如果n秒內高頻時間再次觸發,則重新計算時間。
- const debounce = (fn, time) => {
- let timeout = null;
- return function() {
- clearTimeout(timeout)
- timeout = setTimeout(() => {
- fn.apply(this, arguments);
- }, time);
- }
- };
- 復制代碼
防抖常應用于用戶進行搜索輸入節約請求資源,window觸發resize事件時進行防抖只觸發一次。
12.throttle(節流)
高頻時間觸發,但n秒內只會執行一次,所以節流會稀釋函數的執行頻率。
- const throttle = (fn, time) => {
- let flag = true;
- return function() {
- if (!flag) return;
- flag = false;
- setTimeout(() => {
- fn.apply(this, arguments);
- flag = true;
- }, time);
- }
- }
- 復制代碼
節流常應用于鼠標不斷點擊觸發、監聽滾動事件。
13.函數珂里化
- 指的是將一個接受多個參數的函數 變為 接受一個參數返回一個函數的固定形式,這樣便于再次調用,例如f(1)(2)
經典面試題:實現add(1)(2)(3)(4)=10; 、 add(1)(1,2,3)(2)=9;
- function add() {
- const _args = [...arguments];
- function fn() {
- _args.push(...arguments);
- return fn;
- }
- fn.toString = function() {
- return _args.reduce((sum, cur) => sum + cur);
- }
- return fn;
- }
- 復制代碼
14.模擬new操作
3個步驟:
- 以ctor.prototype為原型創建一個對象。
- 執行構造函數并將this綁定到新創建的對象上。
- 判斷構造函數執行返回的結果是否是引用數據類型,若是則返回構造函數執行的結果,否則返回創建的對象。
- function newOperator(ctor, ...args) {
- if (typeof ctor !== 'function') {
- throw new TypeError('Type Error');
- }
- const obj = Object.create(ctor.prototype);
- const res = ctor.apply(obj, args);
- const isObject = typeof res === 'object' && res !== null;
- const isFunction = typeof res === 'function';
- return isObject || isFunction ? res : obj;
- }
- 復制代碼
15.instanceof
instanceof運算符用于檢測構造函數的prototype屬性是否出現在某個實例對象的原型鏈上。
- const myInstanceof = (left, right) => {
- // 基本數據類型都返回false
- if (typeof left !== 'object' || left === null) return false;
- let proto = Object.getPrototypeOf(left);
- while (true) {
- if (proto === null) return false;
- if (proto === right.prototype) return true;
- proto = Object.getPrototypeOf(proto);
- }
- }
- 復制代碼
16.原型繼承
這里只寫寄生組合繼承了,中間還有幾個演變過來的繼承但都有一些缺陷
- function Parent() {
- this.name = 'parent';
- }
- function Child() {
- Parent.call(this);
- this.type = 'children';
- }
- Child.prototype = Object.create(Parent.prototype);
- Child.prototype.constructor = Child;
- 復制代碼