Skip to content

Latest commit

 

History

History
85 lines (80 loc) · 1.75 KB

13. 常用的js函数.md

File metadata and controls

85 lines (80 loc) · 1.75 KB

13. 常用的js函数

[[toc]]

判断对象是否相等

function isObjectEqual (a = {}, b = {}): boolean {
  // handle null value #1566
  if (!a || !b) return a === b
  const aKeys = Object.keys(a)
  const bKeys = Object.keys(b)
  if (aKeys.length !== bKeys.length) {
    return false
  }
  return aKeys.every(key => {
    const aVal = a[key]
    const bVal = b[key]
    // check nested equality
    if (typeof aVal === 'object' && typeof bVal === 'object') {
      return isObjectEqual(aVal, bVal)
    }
    return String(aVal) === String(bVal)
  })
}

异步执行

function runQueue (queue: Array, fn: Function, cb: Function) {
  const step = index => {
    if (index >= queue.length) {
      cb()
    } else {
      if (queue[index]) {
        fn(queue[index], () => {
          step(index + 1)
        })
      } else {
        step(index + 1)
      }
    }
  }
  step(0)
}

测试:

const calls = []
const queue = [1, 2, 3, 4, 5].map(i => next => {
  calls.push(i)
  console.log(i);
  setTimeout(next, 2000)
})
runQueue(queue, (fn, next) => fn(next), () => {
  console.log(calls)
})

// 15:59:12.079 1
// 15:59:14.067 2
// 15:59:16.071 3
// 15:59:18.073 4
// 15:59:20.077 5
// 15:59:22.079 [1, 2, 3, 4, 5]

重写window.Date,和服务器时间一致

$axios.get('/getServerDate').then(res => {
  let serverDate = new Date(res.headers.date);
  let difference = serverDate - new Date();
  let temp = window.Date;
  window.Date = function() {
    if (arguments.length) {
      return new temp(...arguments);
    } else {
      return new temp(difference + new temp().getTime());
    }
  }
  window.Date.prototype = temp.prototype;
  window.Date.parse = temp.parse;
  window.Date.now = function() {
    return Date().getTime();
  };
})