前端妹子應該掌握的 javascript 基礎

前言

這段時間複習了 js 的基礎,梳理了一下本身的整個知識掌握狀況。 實現並不是最優解,歡迎姐妹們討論和指正,你們一塊兒進步呀。html

js 基礎

包括:防抖、節流、閉包、柯里化、new、bind、apply、call、this、做用域、數據類型、經常使用數組&字符串&正則方法、排序、去重、拍平數組、深拷貝、跨域解決方案、promisenode

  1. 防抖
function debounce_y(func, delay) {
  let timer = null;
  return function (...args) {
    timer && clearTimeout(timer);
    timer = setTimeout(() => {
      func.apply(this, args);
    }, delay);
  };
}
複製代碼
  1. 節流
function trottle_y(func, delay) {
  let start = new Date();
  let timer = null;
  return function (...args) {
    timer && clearTimeout(timer);
    if (new Date() - start >= delay) {
      func.apply(this, args);
      start = new Date();
    } else {
      timer = setTimeout(() => {
        func.apply(this, args);
      }, delay);
    }
  };
}
複製代碼
  1. 閉包
function count() {
  let count = 0;
  return function () {
    count++;
    console.log(count);
  };
}
複製代碼
  1. 柯里化
function curry_y(func) {
  return function curried(...args) {
    if (args.length >= func.length) {
      func.apply(this, args);
    } else {
      return function (...args2) {
        curried.apply(this, args.concat(args2));
      };
    }
  };
}
複製代碼
  1. new 操做符
function new_y(func) {
  let obj = {};
  obj.__proto__ = func.prototype;
  let res = func.apply(this);
  if (res instanceof Object) {
    return res;
  } else {
    return obj;
  }
}
複製代碼
  1. 手寫 bind
// 基礎版
Function.prototype.bind_y = function (obj) {
  let that = this;
  return function (...args) {
    that.apply(obj, args);
  };
};
// 增強版-考慮bind還能夠傳入更多的參數做爲函數的參數
Function.prototype.bind_y = function (obj, ...args0){
  let that = this;
  return function (...args){
    that.apply(obj, args0.concat(args));
  }
}
// 考慮到bind能夠不傳target,不傳時默認爲window
Function.prototype.bind_y = function (){
  let that = this; 
  let target = arguments[0];
  let args0 = Array.prototype.slice.call(arguments, 1);
  return function (...args){
    that.apply(target, args0.concat(args));
  }
}
複製代碼
  1. 手寫 apply
// 借用bind實現
Function.prototype.apply_y = function (obj) {
  return function (...args) {
    this.bind(obj)(args);
  };
};
// 不使用bind實現
Function.prototype.apply_y = function (target, args) {
  !target && (target = window);
  let fn = Symbol();
  target.fn = this;
  args ? target.fn(...args) : target.fn();
  delete target.fn;
};
複製代碼
  1. 手寫 call
Function.prototype.call_y = function (obj) {
  return function (...args) {
    this.bind(obj)(...args);
  };
};
複製代碼
  1. this
// 普通函數中,this指向調用函數的對象,在調用時綁定
var name = "y";
var cat = { name: "miao" };
function a() {
  console.log(this.name);
}
a(); // y
a.apply(cat); // miao

// 箭頭函數中,this繼承自父函數,在聲明時綁定
var name = "y";
var cat = { name: "miao" };
var a = () => {
  console.log(this.name);
};
a(); // y
a.apply(cat); // y
複製代碼
  1. 做用域
// 變量聲明提高
console.log(a); // 1
console.log(b); // Uncaught ReferenceError: b is not defined
console.log(c); // Uncaught ReferenceError: c is not defined
var a = 1;
let b = 2;
const c = 3;

// 函數聲明提高
console.log(y); // ƒ y(){console.log("nice to meet you!")}
function y() {
  console.log("nice to meet you!");
}
複製代碼
  1. 數據類型 基本類型存於棧內存,引用類型存於堆內存,從存取頻率上可理解。
  • 基本類型 Number、 Boolean、String、Undefined、Null、BigInt、Symbolwebpack

  • 引用類型 Object、Array、Function、Date、RegExpweb

typeof 方法能夠判斷基本類型和函數;instanceof 方法能夠判斷引用類型;Object.prototype.toString.call()方法能夠精確判斷全部數據類型。json

  1. 經常使用數組&字符串& 正則方法
// 字符串方法
"abc".split("");
"abc".indexOf("a");
"abc".charAt(0);
"abc".replace("a", 1);
"abc".match("a");
"abc".matchAll("a");

// 數組方法
[1, 2, 3].join("");
[1, 2, 3].indexOf(1);
[1, 2, 3].findIndex((item) => item > 1);
[(1, 2, 3)][0];
[1, 2, 3].reduce((acc, item, index, arr) => {
  return acc + item;
});
[1, 2, 3].map((item, index) => {});
[1, 2, 3].forEach((item, index) => {});
[1, [2, 3]].flat(2);
[1, 2, 3].fill("a");
[1, 2, 3].includes(1);

// 正則方法
/[a-z]/.test("abc");
/([a-z])(?!\1)([a-z])/.exec("aac");
複製代碼
  1. 排序
// sort
[1, 3, 5, 2, 4, 6].sort((a, b) => {
  return a - b;
});

// 快速排序
function quickSort(arr) {
  if (arr.length < 2) return arr;
  let left = [];
  let right = [];
  let flag = arr.splice(arr.length - 1, 1)[0];
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] > flag) {
      right.push(arr[i]);
    } else {
      left.push(arr[i]);
    }
  }
  return quickSort(left).concat(flag, quickSort(right));
}

// 冒泡排序
function bubbleSort(arr) {
  for (let i = 0; i < arr.length - 1; i++) {
    for (let j = i + 1; j < arr.length; j++) {
      if (arr[i] > arr[j]) {
        [arr[i], arr[j]] = [arr[j], arr[i]];
      }
    }
  }
  return arr;
}

// 選擇排序 
function selectSort(arr) {
  let min = 0;
  for (let i = 0; i < arr.length - 1; i++) {
    min = i;
    for (let j = i + 1; j < arr.length; j++) {
      if (arr[j] < arr[min]) {
        min = j;
      }
    }
    [arr[i], arr[min]] = [arr[min], arr[i]];
  }
  return arr;
}
複製代碼
  1. 去重
// new Set
new Set([1, 2, 1, 2]);

// 遍歷
function uniq(arr) {
  for (let i = 0; i < arr.length - 1; i++) {
    for (let j = i + 1; j < arr.length; j++) {
      if (arr[i] === arr[j]) {
        arr.splice(j, 1);
        i--;
      }
    }
  }
  return arr;
}
複製代碼
  1. 拍平數組
// flat
[1, [1, [3, 4]]].flat(3);

// 遞歸
function flat_y(arr) {
  let res = [];
  for (let i = 0; i < arr.length; i++) {
    if (Array.isArray(arr[i])) {
      res = res.concat(flat_y(arr[i]));
    } else {
      res.push(arr[i]);
    }
  }
  return res;
}
複製代碼
  1. 深拷貝
function deepClone_y(obj, map = new Map()) {
  let type = Object.prototype.toString.call(obj);
  if (
    [
      "[object String]",
      "[object Number]",
      "[object Undefined]",
      "object Boolean",
    ].includes(type)
  )
    return obj;
  if (type === "[object Array]") {
    if (map.get(obj)) return map.get(obj);
    let arr = [];
    map.set(obj, arr);
    for (let i = 0; i < obj.length; i++) {
      arr.push(deepClone_y(obj[i], map));
    }
    return arr;
  }
  if (type === "[object Object]") {
    if (map.get(obj)) return map.get(obj);
    let res = {};
    map.set(obj, res);
    for (let key in obj) {
      res[key] = deepClone_y(obj[key], map);
    }
    return res;
  }
  // 函數類型新建函數方法:new Function('參數','函數體')
}
複製代碼
  1. 跨域解決方案 域名協議端口都相同才叫作同源
  • jsonp

藉助script標籤實現跨域 ps: 已通過時了爲何還要考api

  • webpack-dev-server proxy
proxy: {
    '/api': {
        target: 'http://127.0.0.1:7001/',
        changeOrigin: true,
        pathRewrite: {
            '^/api': '/api'
        }
    }
}
複製代碼
  • cors
Access-Control-Allow-Origin: http://www.test.com
Access-Control-Allow-Credentials: true
Access-Control-Expose-Headers: FooBar
Content-Type: text/html; charset=utf-8
複製代碼
  • node server請求轉發
  1. 手寫 promise
class promise_y{
    constructor(executor){
        this.status = 'pending';
        this.value = undefined;
        this.reason = undefined;
        this.successCallbacks = [];
        this.failCallbacks = [];
        let resolve = (data) => {
            if(this.status === 'pending'){
                this.status = 'fullfilled';
                this.value = data;
                this.successCallbacks.forEach(func => func());
            }
        };
        let reject = (data) => {
            if(this.status === 'pending'){
                this.status = 'rejected';
                this.reason = data;
                this.failCallbacks.forEach(func => func());
            }
        }
        try{
            executor(resolve,reject);
        }catch(e){
            reject(e);
        }
    }
    then(onFullfilled, onRejected){
            if(this.status === 'fullfilled'){
                onFullfilled(this.value);
            }
            if(this.status === 'rejected'){
                onRejected(this.reason);
            }
            if(this.status === 'pending'){
                this.successCallbacks.push(() => {
                    onFullfilled(this.value);
                });
                this.failCallbacks.push(() => {
                    onRejected(this.reason)
                })
            }
    }
}
複製代碼

知識點還不完善,能夠做爲複習目錄,後面會繼續完善和更新,歡迎點贊和關注呀。寫代碼的女孩不容易,但請不要放棄,由於你不是一我的在戰鬥,加油。跨域

相關文章
相關標籤/搜索