前端工程師進階之旅-手撕代碼
主要包括一些工作中常用的方法,面試常問到的方法。還有一些不太了解,趁機深入了解的知識點。都弄懂之后還是有點提升的。
數據類型判斷
function myTypeof(data) {
return Object.prototype.toString.call(data).slice(8, -1).toLowerCase();
}
數組去重
//new Set() 集合
//ES6提供了新的數據結構Set。它類似於數組,但是成員的值都是唯一的,沒有重復的值。
function unique(arr) {
return [...new Set(arr)];
}
//數組去重 filter
function unique(arr) {
return arr.filter((item, index, array) => {
return array.indexOf(item) === index;
});
}
// 數組去重 forEach
function unique(arr) {
let res = [];
arr.forEach((item) => {
res.includes(item) ? "" : res.push(item);
});
return res;
}
數組排序
// 快排排序
function quickSort(arr) {
// 數組長度為1 直接返回
if (arr.length <= 1) return arr;
var left = [],
right = [];
var centerIndex = Math.floor(arr.length / 2);
// 定義中間值
var center = arr[centerIndex];
for (let i = 0; i < arr.length; i++) {
// 小於中間值數據添加到left
if (arr[i] < center) {
left.push(arr[i]);
} else if (arr[i] > center) {
// 大於中間值數據添加到right
right.push(arr[i]);
}
}
// 遞歸返回 concat連接返回數據
return quickSort(left).concat([center], quickSort(right));
}
// 冒泡排序
function bubbleSort(arr) {
for (var i = 0; i < arr.length - 1; i++) {
for (var j = i + 1; j < arr.length; j++) {
if (arr[i] > arr[j]) {
var temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
}
}
return arr;
}
數組扁平化
//使用 Infinity,可展開任意深度的嵌套數組
arr.flat(Infinity);
//適用JSON轉換
JSON.parse("[" + JSON.stringify(arr).replace(/\[|\]/g, "") + "]");
//遞歸
function myFlat(arr) {
let res = [];
arr.forEach((item) => {
if (Array.isArray(item)) {
res = res.concat(myFlat(item));
} else {
res.push(item);
}
});
return res;
}
//some
function myFlat(arr) {
while (arr.some((res) => Array.isArray(res))) {
arr = [].concat(...arr);
}
return arr;
}
回文字符串相關
//回文:正讀和反讀都一樣的字符串。
//判斷是否是回文字符串
function isPalindrome(str) {
if (!str) return false
return str == str.split("").reverse().join("")
}
//找出字符串中最長的回文字段
//循環暴力破解
function palindrome(str) {
var len = str.length
var maxStr = ''
if (isPalindrome(str)) return str
for (let i = 0; i <= len - 1; i++) {
for (let j = i + 1; j <= len; j++) {
var s = str.slice(i, j)
if (!isPalindrome(s)) continue
if (s.length > maxStr.length) {
maxStr = s
}
}
}
return maxStr
}
//改造方法 中心擴展法
function palindrome(str) {
var len = str.length
var s = ''
if (len < 2) return str
for (let i = 0; i < len; i++) {
/**判斷是否是回文,i作為回文中間值,有兩種可能 */
isPalindrome(i, i)
isPalindrome(i, i + 1)
}
function isPalindrome(i, j) {
while (i >= 0 && j <= len && str[i] == str[j]) {
i--
j++
}
// 判斷是否是最長回文
if (j - i - 1 > s.length) {
s = str.slice(i + 1, j)
}
}
return s
}
深拷貝深克隆
// 簡單克隆 無法復制函數
var newObj = JSON.parse(JSON.stringify(obj));
// 深克隆 無法克隆特殊實例 Date等
function deepClone(target) {
if (typeof target !== "object") {
return target;
}
var result;
if (Object.prototype.toString.call(target) == "[object Array]") {
// 數組
result = [];
} else {
// 對象
result = {};
}
for (var prop in target) {
if (target.hasOwnProperty(prop)) {
result[prop] = deepClone(target[prop]);
}
}
return result;
}
//復雜版深克隆
function deepClone(target) {
if (typeof target !== "object") return target;
// 檢測RegDate類型創建特殊實例
let constructor = target.constructor;
if (/^(RegExp|Date)$/i.test(constructor.name)) {
return new constructor(target);
}
// 判斷類型
var result =
Object.prototype.toString.call(target) == "[object Array]" ? [] : {};
// 迭代循環
for (var prop in target) {
if (target.hasOwnProperty(prop)) {
// 遞歸
result[prop] = deepClone(target[prop]);
}
}
return result;
}
繼承方法
原型鏈繼承:
// 原型鏈繼承
// 問題:原型中的引用對象會被所有的實例共享,子類在實例化的時候不能給父類構造函數傳參
function Father() {
this.hobby = ["coding", "eat"];
}
Father.prototype.skill = function () {
console.log("i will javascript");
};
function Son() {}
Son.prototype = new Father();
var father = new Father();
var son = new Son();
var son1 = new Son();
console.log(father.hobby); //[ 'coding', 'eat' ]
father.hobby.push("play");
console.log(father.hobby, son.hobby, son1.hobby);
//[ 'coding', 'eat', 'play' ] [ 'coding', 'eat' ] [ 'coding', 'eat' ]
son.hobby.push("hei");
console.log(father.hobby, son.hobby, son1.hobby);
//[ 'coding', 'eat', 'play' ] [ 'coding', 'eat', 'hei' ] [ 'coding', 'eat', 'hei' ]
son.skill(); //i will javascript
借用構造函數實現繼承
// 原型鏈繼承
// 問題:方法需要定義在構造函數內,因此每次創建子類實例都會創建一邊方法
function Father(name) {
this.name = name;
this.sayNmae = function () {
return this.name;
};
}
function Son(name) {
Father.call(this, name);
}
Son.prototype = new Father();
var father = new Father("wenbo");
var son = new Son("zhijian");
console.log(father.name, son.name); //wenbo zhijian
console.log(father.sayNmae(), son.sayNmae()); //wenbo zhijian
組合繼承
//組合繼承,結合原型鏈繼承和借用構造函數,使用原型鏈繼承原型上的屬性和方法,借用構造函數繼承實例屬性。
//即可以把方法定義在原型上實現重用,又可以讓每個實例都有自己的屬性
// 組合繼承
function Father(name) {
this.name = name;
}
Father.prototype.sayName = function () {
return this.name;
};
function Son(name, age) {
Father.call(this, name);
this.age = age;
}
Son.prototype = new Father();
Son.prototype.constructor = Son;
var son = new Son("yewen", 18);
console.log(son); //Son { name: 'yewen', age: 18 }
console.log(son.sayName()); //yewen
寄生式組合繼承
//寄生組合繼承
// 組合繼承會導致調用兩次父類構造函數
function Father(name) {
this.name = name;
}
Father.prototype.sayName = function () {
return this.name;
};
function Son(name, age) {
Father.call(this, name);
this.age = age;
}
Son.prototype = Object.create(Father.prototype);
Son.prototype.constructor = Son;
class 實現繼承
// calss繼承
class Father {
constructor(name) {
this.name = name;
}
getName() {
return this.name;
}
}
class Son extends Father {
constructor(name, age) {
super(name);
this.age = age;
}
getAge() {
return this.age;
}
}
var son = new Son("heihei", 18);
console.log(son); //Son { name: 'heihei', age: 18 }
console.log(son.getName(), son.getAge()); //heihei 18
事件總線(發布訂閱模式)
class EventEmitter {
constructor() {
this.cache = {};
}
on(name, fn) {
if (this.cache[name]) {
this.cache[name].push(fn);
} else {
this.cache[name] = [fn];
}
}
off(name, fn) {
let tasks = this.cache[name];
if (tasks) {
const index = tasks.findIndex((f) => f === fn || f.callback === fn);
index >= 0 ? tasks.splice(index, 1) : "";
}
}
emit(name, once, ...args) {
if (this.cache[name]) {
// 創建副本
let tasks = this.cache[name].slice();
for (const fn of tasks) {
fn(...args);
}
once ? delete this.cache[name] : "";
}
}
}
let demo = new EventEmitter();
demo.on("wenbo", function (data) {
console.log("wenbo", data);
});
let fn1 = function (data) {
console.log("hello:", data);
};
demo.on("wenbo", fn1);
demo.emit("wenbo", false, "world");
demo.off("wenbo", fn1);
demo.emit("wenbo", false, "world");
//wenbo world
//hello: world
//wenbo world
獲得滾動距離
function getScrollOffset() {
if (window.pageXOffset) {
return {
x: window.pageXOffset,
y: window.pageYOffset,
};
} else {
return {
x: document.body.scrollLeft + document.documentElement.scrollLeft,
y: document.body.scrollTop + document.documentElement.scrollTop,
};
}
}
獲得視口尺寸
function getViewportOffset() {
if (window.innerWidth) {
return {
w: window.innerWidth,
h: window.innerHeight,
};
} else {
// ie8及其以下
if (document.compatMode === "BackCompat") {
// 怪異模式
return {
w: document.body.clientWidth,
h: document.body.clientHeight,
};
} else {
// 標准模式
return {
w: document.documentElement.clientWidth,
h: document.documentElement.clientHeight,
};
}
}
}
防抖函數
function debounce(fun, wait) {
var timeId = null;
return function () {
var _this = this;
var _arg = arguments;
clearTimeout(timeId);
timeId = setTimeout(function () {
fun.apply(_this, _arg);
}, wait);
};
}
節流函數
function throttle(fun, wait) {
var lastTime = 0;
return function () {
var _this = this;
var _arg = arguments;
var nowTime = new Date().getTime();
if (nowTime - lastTime > wait) {
fun.apply(_this, _arg);
lastTime = nowTime;
}
};
}
圖片加載優化懶加載
// 獲取全部img元素 並且將類數組轉化成數組
let imgList = [...document.querySelectorAll("img")];
let len = imgList.length;
// 圖片懶加載
function imgLazyLoad() {
let count = 0;
return (function () {
let isLoadList = [];
imgList.forEach((item, index) => {
let h = item.getBoundingClientRect();
// 判斷圖片是否快要滾動道可視區域
if (h.top < window.innerHeight + 200) {
item.src = item.dataset.src;
console.log(item.dataset.src);
isLoadList.push(index);
count++;
// 全部加載 移出scroll事件
if (len == count) {
document.removeEventListener("scroll", imgLazyLoad);
}
}
});
// 移出已經加載完成的圖片
imgList = imgList.filter((img, index) => !isLoadList.includes(index));
})();
}
// 節流函數
function throttle(fun, wait) {
var lastTime = 0;
return function () {
var _this = this;
var _arg = arguments;
var nowTime = new Date().getTime();
if (nowTime - lastTime > wait) {
fun.apply(_this, _arg);
lastTime = nowTime;
}
};
}
// 默認執行一次加載首屏圖片
imgLazyLoad();
// 節流執行
document.addEventListener("scroll", throttle(imgLazyLoad, 200));
綁定事件
function addEvent(elem, type, handle) {
if (elem.addEventListener) {
//非ie和ie9以上
elem.addEventListener(type, handle, false);
} else if (elem.attachEvent) {
//ie8以下 ie6-8
elem.attachEvent("on" + type, function () {
handle.call(elem);
});
} else {
// 其他
elem["on" + type] = handle;
}
}
解綁事件
function removeEvent(elem, type, handle) {
if (elem.removeEventListener) {
//非ie和ie9以上
elem.removeEventListener(type, handle, false);
} else if (elem.detachEvent) {
//ie8以下 ie6-8
elem.detachEvent("on" + type, handle);
} else {
//其他
elem["on" + type] = null;
}
}
取消冒泡事件
function stopBubble(e) {
//兼容ie9以下
if (e && e.stopPropagation) {
e.stopPropagation();
} else {
window.event.cancelBubble = true;
}
}
JS 創建 Script
function loadScript(url, callback) {
var script = document.createElement("script");
if (script.readyState) {
// 兼容ie8及以下版本
script.onreadystatechange = function () {
if (script.readyState === "complete" || script.readyState === "loaded") {
// 回調函數
callback();
}
};
} else {
// 加載完成之后
script.onload = function () {
// 回調函數
callback();
};
}
script.src = url;
// 添加標簽
document.body.appendChild(script);
}
管理操作 Cookie
var cookie = {
//設置cookie
set: function (name, value, time) {
document.cookie = `${name}=${value};expires=${time};path=/`;
return this;
},
//獲取cookie
get: function (name) {
var arr;
var reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
if ((arr = document.cookie.match(reg))) {
return unescape(arr[2]);
} else {
return null;
}
},
//移出token
remove: function (name) {
return this.setCookie(name, "", -1);
},
};
驗證郵箱
function isAvailableEmail(email) {
var reg = /^([\w+\.])+@\w+([.]\w+)+$/;
return reg.test(email);
}
封裝 myForEach 方法
// thisValue 可選參數。當執行回調函數 callback 時,用作 this 的值。
Array.prototype.myForEach = function (callback, thisValue) {
var _this;
// 當this為空拋出異常
if (this == null) {
throw new TypeError(" this is null or not defined");
}
// var len = this.length
// this.length >>> 0 相當於 所有非數值轉換成0 ,所有大於等於 0 等數取整數部分
var len = this.length >>> 0;
// callback不是函數時 拋出異常
if (typeof callback !== "function") {
throw new TypeError(callback + " is not a function");
}
// 判斷是夠有傳參 thisValue
if (arguments.length > 1) {
_this = thisValue;
}
// 循環遍歷
for (var i = 0; i < len; i++) {
// 回調函數
callback.call(_this, this[i], i, this);
}
};
封裝 myFilter 方法
Array.prototype.myFilter = function (callback, thisValue) {
var _this;
var arr = [];
if (this == null) {
throw new TypeError(" this is null or not defined");
}
var len = this.length >>> 0;
if (typeof callback !== "function") {
throw new TypeError(callback + " is not a function");
}
if (arguments.length > 1) {
_this = thisValue;
}
for (var i = 0; i < len; i++) {
callback.call(_this, this[i], i, this) && arr.push(this[i]);
}
return arr;
};
封裝 myMap 方法
Array.prototype.myMAp = function (callback, thisValue) {
var _this;
var arr = [];
if (this == null) {
throw new TypeError(" this is null or not defined");
}
var len = this.length >>> 0;
if (typeof callback !== "function") {
throw new TypeError(callback + " is not a function");
}
if (arguments.length > 1) {
_this = thisValue;
}
for (var i = 0; i < len; i++) {
arr.push(callback.call(_this, this[i], i, this));
}
return arr;
};
封裝 myEvery 方法
Array.prototype.myEvery = function (callback, thisValue) {
var _this;
if (this == null) {
throw new TypeError(" this is null or not defined");
}
var len = this.length >>> 0;
if (typeof callback !== "function") {
throw new TypeError(callback + " is not a function");
}
if (arguments.length > 1) {
_this = thisValue;
}
for (var i = 0; i < len; i++) {
if (!callback.call(_this, this[i], i, this)) {
return false;
}
}
return true;
};
封裝 myReduce 方法
Array.prototype.myEvery = function (callback, initialValue) {
var value = 0;
console.log(value);
if (this == null) {
throw new TypeError(" this is null or not defined");
}
var len = this.length >>> 0;
if (typeof callback !== "function") {
throw new TypeError(callback + " is not a function");
}
if (arguments.length > 1) {
value = initialValue;
}
for (var i = 0; i < len; i++) {
value = callback(value, this[i], i, this);
}
return value;
};
獲取 URL 參數
function getURLParam(url) {
let obj = {};
url.replace(/(?<=[?|&])(\w+)=(\w+)/g, function (data, key, value) {
if (obj[key]) {
obj[key] = [].concat(obj[key], value);
} else {
obj[key] = value;
}
});
return obj;
}
HTML 字符串模板
function render(template, data) {
return template.replace(/\{(\w+)}/g, function ($1, key) {
return data[key] ? data[key] : "";
});
}
let html = "我叫{name},今年{id}歲。";
let data = {
name: "Yevin",
age: 18,
};
render(html, data); //我叫Yevin,今年18歲
利用 JSONP 實現跨域請求
function jsonp(url, callbackName) {
return new Promise((resolve, reject) => {
var script = document.createElement("script");
script.src = "demo.js";
document.body.appendChild(script);
window[callbackName] = function (res) {
//移除remove
script.remove();
//返回數據
resolve(res);
};
});
}
原生 JS 封裝 AJAX
function Ajax(method, url, callback, data, async = true) {
var xhr;
//同一轉換method方法為大寫
method = method.toUpperCase();
// 開啟XMLHTTPRequest
xhr = new XMLHttpRequest();
// 監控狀態變化 執行回調函數
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.readyState == 200) {
// 回調函數返回參數
callback(xhr.responseText);
}
};
// 判斷請求方式 get post或者其他
if (method == "GET") {
xhr.open("GET", url, async);
} else if (method == "POST") {
xhr.open("POST", url, async);
// 設置請求頭
xhr.setRequestHeader("Content-Type", "application/json");
// 發送參數
xhr.send(data);
}
}
格式化時間
// formatDate 時間格式,data默認為當前時間
function formatDate(formatDate, date = new Date()) {
var obj = {
yyyy: date.getFullYear(), //4位數年份
yy: ("" + date.getFullYear()).slice(-2), //2位數年份,最后兩位
M: date.getMonth() + 1, //月份
MM: ("0" + (date.getMonth() + 1)).slice(-2), //2位數月份
d: date.getDate(), //日份
dd: ("0" + date.getDate()).slice(-2), //2位數 日份
H: date.getHours(), //小時 24小時制
HH: ("0" + date.getHours()).slice(-2), //2位數小時 24小時制
h: date.getHours() % 12, //小時 12小時制
hh: ("0" + (date.getHours() % 12)).slice(-2), //2位數小時 12小時制
m: date.getMinutes(), //分
mm: ("0" + date.getMinutes()).slice(-2), //2位數分
s: date.getSeconds(), //秒
ss: ("0" + date.getSeconds()).slice(-2), //兩位數秒
w: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"][
date.getDay()
], //星期
};
// 根據傳入字符串使用正則替換相關數據
return formatDate.replace(/([a-z]+)/gi, function ($1) {
return obj[$1];
});
}
函數柯里化
//把多個參數的函數變換成接受一個單一參數的函數,並且返回接受余下的參數且返回結果的新函數的技術
function curry(fun) {
let fn = function (...arg) {
if (arg.length == fun.length) return fun(...arg);
return (...arg2) => fn(...arg, ...arg2);
};
return fn;
}
function demo(a, b) {
return a * b;
}
console.log(demo(1, 2)); //2
console.log(curry(demo)(1)(2)); //2
偏函數
// 偏函數,就是固定一個函數的一個或者多個參數,返回一個新的函數,這個函數用於接受剩余的參數。
function partial(fn, ...arg) {
return function (...args) {
return fn(...arg, ...args);
};
}
function demo(a, b, c) {
console.log(a, b, c); // 1, 2,3
}
var a = partial(demo, 1);
a(2, 3);
在元素后面插入新元素
function insertAfter(target, ele) {
//查看是否有兄弟元素
var nextEle = ele.nextElementSibling;
if (nextEle == null) {
// 無兄弟元素,直接添加到當前元素之后
this.appendChild(target);
} else {
// 若有兄弟元素,添加在下一個兄弟元素之前
this.insertBefore(target, nextEle);
}
}