常见应用题demo

154 阅读1分钟

根据学习和面试经历不定期更新

  • throttle
function throttle(fun, time) {
    let now = Date.now()
    return function() {
        let last = Date.now()
        if(last - now > time) {
            fun.apply(this, arguments)
            now = last
        }
    }
}
  • debounce
function debounce(fun, time) {
    let timer = null
    let now = Date.now()
    return function() {
        clearTimeout(timer)
        timer = settimeout(() => {
            fn.apply(this, arguments)
        }, time)
    }
}
  • platform 多维数组变一维
function platform(arr) {
      return arr.reduce((total, item) => {
        if (Array.isArray(item)) {
            total = total.concat(...platform(item));
        } else {
            total.push(item)
        }
        return total
    }, [])
}
let arr = [1, [2, [3, [4, [5, 6, [7, 8, [9]]]]]]]
platform(arr)
arr.flat(Infinity)
  • 数组去重、乱序、排序
Array.from(new Set(arr))
arr.sort(() => {
        return Math.random()> .5? -1 : 1
    })
  • 深拷贝
 function deepCopy(obj) {
      if(Object.prototype.toString.call(obj) == '[object Object]') {
          let res = {}
          for(let i in obj) {
              if(typeof(i) == 'object') {
                  res[i] = deepCopy(i)
              } else {
                  res[i] = obj[i]
              }
          }
          return res
      } else {
          return false
      }
    }