1、防抖
/** * 防抖,当某一事件触发结束后,然后再去触发相应的函数 * */ function debounce(func, ms = 1000) { let timer; return function (...args) { if (timer) { clearTimeout(timer) } timer = setTimeout(() => { func.apply(this, args) }, ms) } } // 测试 const task = () => { console.log('run task') } const debounceTask = debounce(task, 1000) window.addEventListener('scroll', debounceTask)
2、节流
/** * 节流,在事件执行时,多长时间触发一次执行的函数 * */ function throttle(func, ms = 1000) { let canRun = true return function (...args) { if (!canRun) return canRun = false setTimeout(() => { func.apply(this, args) canRun = true }, ms) } } // 测试 const task = () => { console.log('run task') } const throttleTask = throttle(task, 1000) window.addEventListener('scroll', throttleTask)
3、深复制
注:此方法不能复制dom和二进制
function cloneObj(source, target) { if (!target) { if (source.constructor === RegExp) { target = new RegExp(source.source, source.flags); } else { target = new source.constructor(); } } var names = Object.getOwnPropertyNames(source); for (var i = 0; i < names.length; i++) { var desc = Object.getOwnPropertyDescriptor(source, names[i]); if (typeof desc.value === "object" && desc.value !== null) { var values = cloneObj(desc.value); Object.defineProperty(target, names[i], { enumerable: desc.enumerable, configurable: desc.configurable, writable: desc.writable, value: values }); } else { Object.defineProperty(target, names[i], desc); } } return target; }
4、数组扁平化
// 方案 1 function recursionFlat(ary = []) { const res = [] ary.forEach(item => { if (Array.isArray(item)) { res.push(...recursionFlat(item)) } else { res.push(item) } }) return res } // 方案 2 function reduceFlat(ary = []) { return ary.reduce((res, item) => res.concat(Array.isArray(item) ? reduceFlat(item) : item), []) } // 测试 const source = [1, 2, [3, 4, [5, 6]], '7'] console.log(recursionFlat(source)) console.log(reduceFlat(source))
5、对象扁平化
function objectFlat(obj = {}) { const res = {} function flat(item, preKey = '') { Object.entries(item).forEach(([key, val]) => { const newKey = preKey ? `${preKey}.${key}` : key if (val && typeof val === 'object') { flat(val, newKey) } else { res[newKey] = val } }) } flat(obj) return res } // 测试 const source = { a: { b: { c: 1, d: 2 }, e: 3 }, f: { g: 2 } } console.log(objectFlat(source));
6、promise
// 建议阅读 [Promises/A+ 标准](https://promisesaplus.com/)
class MyPromise {
constructor(func) {
this.status = 'pending'
this.value = null
this.resolvedTasks = []
this.rejectedTasks = []
this._resolve = this._resolve.bind(this)
this._reject = this._reject.bind(this)
try {
func(this._resolve, this._reject)
} catch (error) {
this._reject(error)
}
}
_resolve(value) {
setTimeout(() => {
this.status = 'fulfilled'
this.value = value
this.resolvedTasks.forEach(t => t(value))
})
}
_reject(reason) {
setTimeout(() => {
this.status = 'reject'
this.value = reason
this.rejectedTasks.forEach(t => t(reason))
})
}
then(onFulfilled, onRejected) {
return new MyPromise((resolve, reject) => {
this.resolvedTasks.push((value) => {
try {
const res = onFulfilled(value)
if (res instanceof MyPromise) {
res.then(resolve, reject)
} else {
resolve(res)
}
} catch (error) {
reject(error)
}
})
this.rejectedTasks.push((value) => {
try {
const res = onRejected(value)
if (res instanceof MyPromise) {
res.