• js出场率极高的代码


    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.then(resolve, reject)
              } else {
                reject(res)
              }
            } catch (error) {
              reject(error)
            }
          })
        })
      }
    
      catch(onRejected) {
        return this.then(null, onRejected);
      }
    }
    
    // 测试
    new MyPromise((resolve) => {
      setTimeout(() => {
        resolve(1);
      }, 500);
    }).then((res) => {
        console.log(res);
        return new MyPromise((resolve) => {
          setTimeout(() => {
            resolve(2);
          }, 500);
        });
      }).then((res) => {
        console.log(res);
        throw new Error('a error')
      }).catch((err) => {
        console.log('==>', err);
      })
  • 相关阅读:
    利用数据库复制技术 实现MSSQL数据同步更新
    育子两篇你会教育自已的小孩吗
    hdu 1046 Gridland (找规律题)
    hdu 1022 Train Problem I (栈的操作,还水了半天)
    hdu 4022 Bombing (强大的map一对多的映射)
    POJ 1702 Eva's Balance (数论,平衡三进制)
    hdu 3951 Coin Game (博弈)
    hdu 1058 Humble Numbers (DP初步)
    hdu 2084 数塔 (DP初步)
    hdu 1056 HangOver (打表水题)
  • 原文地址:https://www.cnblogs.com/jingguorui/p/13716853.html
Copyright © 2020-2023  润新知