sleep函数
// 延迟执行
function sleep(time) {
return new Promise((resolve)=> {
setTimeout(resolve, time);
})
}
// 用法
async function test() {
console.log('start')
await sleep(2000)
console.log('end')
}
test()
对象转数组操作
// 对象里面 如下:{1:222, 2:123, 5:888},请把数据处理为如下结构:[222, 123, null, null, 888, null, null]
function convert(obj) {
return Array.from({ length: 12 }).map((item, index) => {
obj[index] || null
}
}
获取url参数
function getParams() {
const url = window.location.href;
const search = url.split('?');
if(!search[1]) return
const params = search[1].split("&");
const obj = {};
for(let i = 0; i < params.length; i++) {
const data = params[i].split('=')
obj[data[0]] = data[1];
}
return obj
}
函数柯里化
函数柯里化提供了更灵活、可复用和可组合的函数编程方式,使得函数的使用和定制更加方便。它在函数式编程和一些特定的编程场景中非常有用,可以提高代码的可读性和可维护性。
//接收一部分参数,返回一个函数接收剩余参数,接收足够参数后,执行原函数。
function curried(fn,...args) {
if (args.length < fn.length) {
return (...rest) => curried(fn, ...args, ...rest)
} else {
return fn(...args);
}
}
function add(a, b, c) {
return a + b + c;
}
console.log(curried(add, 1)(2)(3))
console.log(curried(add, 1, 2)(3))
手写一个Object.create()
// 创建一个新对象并将其原型设置为指定对象的方法
function (obj) {
if(typeof obj !== "object" && typeof obj !== "function") {
throw new TypeError("Object prototype may only be an Object or null.");
};
function F() {};// 创建一个空的构造函数
F.prototype = obj;// 将构造函数的原型指向传入的对象
return new F();// 返回一个新的实例对象,该对象的原型为传入的对象
}
手写一个new执行过程
- 创建一个空对象
- 将对象的__proto__指向构造函数的prototype
- 将这个对象作为构造函数的 this
- 确保返回值为对象,如果构造函数返回了一个对象,则返回该对象;否则返回步骤 1 中创建的空对象。
function mynew(con, ...args) {
let obj = Object.create(con.prototype);
let result = con.apply(obj, args);
return typeof result === 'object' ? result : obj;
}
节流防抖
// 节流
function throttle(fn, delay) {
let timer;
return (...args) => {
if(!timer) return;
timer = setTimeout(() => {
fn.apply(this, args);
timer = null;
}, delay)
}
}
// 防抖
function debounce(fn, delay) {
let timer;
return (...args) => {
timer && clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(this, args);
timer = null;
}, delay)
}
}
实现深拷贝
function deepclone(obj) {
if (typeof obj !== "object" || typeof obj !== null) {
return obj;
}
let copy;
if (Array.isArray(obj)) {
copy = [];
for (let i = 0; i < obj.length; i++) {
copy[i] = deepclone(obj[i]);
}
} else {
copy = {};
for (let i in obj) {
if (obj.hasOwnProperty(i)) {
copy[i] = deepclone(obj[i]);
}
}
}
return copy;
}
数据扁平化
function _flat(arr, depth) {
if (!Array.isArray(arr) || depth <= 0) {
return arr
}
return arr.reduce((prev, cur) => {
if (Array.isArray(cur)) {
return prev.concat(_flat(cur, depth - 1))
} else {
return prev.concat(cur)
}
}, [])
}