js实现七天内签到功能

·  阅读 143

功能:实现七天为一个周期签到功能。

思路:

  • 将签到时间存为一个数组
  • 判断当日是否已经签过到

1.已经签过到:直接使用存入的数组判断激活状态
2.未签过到:
(1) 没有签到记录:空数组
(2) 有签到记录:计算上次签到与当次签到相隔天数

  • 将相隔天数与数组剩余位置对比

1.小于:该数组中推出相隔天数的空值和当天的日期
2.大于等于:启动下一个周期

测试数据

//从未签过到
  let signArr=[]
  let signIn=false
  
//当日未签到
let signArr=["2021-11-21",false,"2021-11-23"]
let signIn=false

//已经签到过
let signArr = ["2021-11-21","2021-11-22"]
let signIn=true

//签到下一轮
let signArr=['2021-11-15','2021-11-16']
let signIn=false

let signArr = ['2021-10-1', false, '2021-10-3']
let signIn = false

复制代码

具体代码实现如下

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <ul></ul>
  <button>签到</button>
  <script>

   let signArr = ['2021-11-20', false, '2021-11-22']
   let signIn = false

    function getIntervalDay(a, b) {
      if (!a || !b) return 0

      a = a.split('-').map(item => +item)
      b = b.split('-').map(item => +item)

      const currentTime = new Date(a[0], a[1] - 1, a[2]).getTime()

      const lastTime = new Date(b[0], b[1] - 1, b[2]).getTime()
      return (currentTime - lastTime) / 1000 / 60 / 60 / 24 - 1
    }

    function getActiveArr(signArr, signIn) {
      if (!signIn && signArr.length) {
        const currentDate = new Date()
        const intervalDay = getIntervalDay(
          `${currentDate.getFullYear()}-${currentDate.getMonth() + 1}-${currentDate.getDate()}`,
          signArr[signArr.length - 1]
        )
    //获取当天时间
  console.log(`${currentDate.getFullYear()}-${currentDate.getMonth() + 1}-${currentDate.getDate()}`)

        if (intervalDay < 7 - signArr.length) {
          return signArr
        } else {
          return []
        }
      } else {
        return signArr
      }
    }

    // 展示列表
    function render(ActiveArr) {
      ul.innerHTML = ''
      for (let i = 0; i < 7; i++) {
        const li = document.createElement('li')
        li.innerText = ActiveArr[i]
        ul.appendChild(li)
      }
    }
    
    const ul = document.querySelector('ul')
    const btn = document.querySelector('button')
    let ActiveArr = getActiveArr(signArr, signIn)
    render(ActiveArr)

    // 签到
    btn.onclick = function () {
      if (signIn) return alert('已经签过到了')

      const currentDate = new Date()
      const currentDay = `${currentDate.getFullYear()}-${currentDate.getMonth() + 1}-${currentDate.getDate()}`

      const intervalDay = getIntervalDay(
        currentDay,
        ActiveArr[ActiveArr.length - 1]
      )

      if (intervalDay < 7 - ActiveArr.length) {
        ActiveArr.push(...new Array(intervalDay).fill(false))
      } else {
        ActiveArr = []
      }

      ActiveArr.push(currentDay)
      signArr = ActiveArr
      signIn = true
      render(ActiveArr)
    }



  </script>
</body>

</html>
复制代码
分类:
前端
标签:
分类:
前端
标签: