js的常用方法集合

// 对比开始时间以及结束时间大小(例如:23:22:22)

const validTime = function(startTime, endTime) {

  if (time_to_sec(endTime) - time_to_sec(startTime) > 0) {

    return true

  }

  return false

}

// 将时分秒转为时间戳

const  time_to_sec = function(time) {

  if (time !== null) {

    var s = ''

    var hour = time.split(':')[0]

    var min = time.split(':')[1]

    var sec = time.split(':')[2]

    s = Number(hour * 3600) + Number(min * 60) + Number(sec)

    return s

  }

}

//  按钮防重复点击

var clickTimer = 0

const clickThrottle = function(interval = 3000) {

  const now = +new Date() // 获取当前时间的时间戳

  const timer = clickTimer // 记录触发事件的事件戳

  if (now - timer < interval) {

    // 如果当前时间 - 触发事件时的事件 < interVal,那么不符合条件,直接return false,

    // 不让当前事件继续执行下去

    return false

  } else {

    // 反之,记录符合条件触发了事件的时间戳,并 return true,使事件继续往下执行

    clickTimer = now

    return true

  }

}

// 字符串年月拼接

const setMonth = function() {

  let date = new Date()// 获取当前日期

  date = date.getTime()// 把当前日期转换为时间戳

  // 把时间戳转换为日期格式

  const newDate = new Date(parseInt(date))

  var y = newDate.getFullYear()

  var m = newDate.getMonth() + 1

  m = m < 10 ? ('0' + m) : m

  return y + '-' + m

}

// 对象属性去重

const removeDuplicateObj = function(arr) {

  var obj = {}

  arr = arr.reduce(function(item, next) {

    obj[next.key] ? '' : obj[next.key] = true && item.push(next)

    return item

  }, [])

  return arr

}

猜你喜欢

转载自blog.csdn.net/weixin_43832782/article/details/129260172
今日推荐