1.debounce防抖
functioin debounce(fn, delay) {
let timer
return function () {
clearTimeout(timer)
let _this = this
let arg = arguments
timer = setTimeout(function() {
fn.apply(_this, arg)
},delay)
}
}
2.throttle节流
function throttle(fn,delay) {
let timer
return function() {
let _this = this
let arg = arguments
if(!timer){
timer = setTimerout(function(){
fn.apply(_this, arg)
timer = null
},delay)
}
}
}
3.深拷贝
function deepClone(obj) {
if(typeof obj !== 'object' || obj === null) {
return obj
}
let res
if(obj instanceof Array) {
res = []
}else{
res = {}
}
for(let key in obj) {
if(obj.hasOwnProperty(key)) {
res[key] = deepClone(obj[key])
}
}
return res
}
4.bind
Function.prototype.mybind = function() {
let arr = Array.prototype.slice.call(arguments)
let _this = arr.shift()
let fn = this
return function() {
return fn.apply(_this, arr)
}
}
5.call
Function.prototype.call2 = function(content = window) {
content.fn = this;
let args = [...arguments].slice(1);
let result = content.fn(...args);
delete content.fn;
return result;
}
6.apply
Function.prototype.apply2 = function(context = window) {
context.fn = this
let result;
if(arguments[1]) {
result = context.fn(...arguments[1])
} else {
result = context.fn()
}
delete context.fn
return result
}
5.数组去重
function unique(arr) {
let res = []
arr.forEach(item) {
if(res.indexOf(item) < 0) {
res.push(item)
}
}
return res
}
7.数组扁平化
function flat(arr) {
let isDeep = arr.some(item => item instanceof Array)
if(!isDeep) {
return arr
}
let res = Array.prototype.concat.applay([], arr)
return flat(res)
}
深度比较isEqual
function isEqual(obj1, obj2) {
if (typeof obj1 === typeof obje2) {
if (typeof obj1 === 'object') {
const objKey1s = Object.keys(obj1)
const objKey2s = Object.keys(obj2)
if (objKey1s.length !== objKey2s.length) {
return false
} else {
if (obj1 instanceof Array === obj2 instanceof Array || obj1 instanceof Object === obj2 instanceof Object) {
for (let key in obj1) {
const res = isEqual(obj1[key], obj2[key])
if (!res) {
return false
}
}
}else {
return false
}
}
} else {
if (obj1 === obj2) {
return true
} else {
return false
}
}
} else {
return false
}
}
new
function New(func) {
var res = {};
if (func.prototype !== null) {
res.__proto__ = func.prototype;
}
var ret = func.apply(res, Array.prototype.slice.call(arguments, 1));
if ((typeof ret === "object" || typeof ret === "function") && ret !== null) {
return ret;
}
return res;
}
promise
function myPromise(constructor){
let self=this;
self.status="pending"
self.value=undefined;
self.reason=undefined;
function resolve(value){
if(self.status==="pending"){
self.value=value;
self.status="resolved";
}
}
function reject(reason){
if(self.status==="pending"){
self.reason=reason;
self.status="rejected";
}
}
try{
constructor(resolve,reject);
}catch(e){
reject(e);
}
}
myPromise.prototype.then=function(onFullfilled,onRejected){
let self=this;
switch(self.status){
case "resolved":
onFullfilled(self.value);
break;
case "rejected":
onRejected(self.reason);
break;
default:
}
}