1、平时工作中我们也许会遇到这种情况,返回一个数组,每个数组会有一个时间戳,我们需要将数组中的每一项按照日期分到不同组 2、效果:
3、主要实现的想法是:先遍历数组中的时间戳然后将其转成日期,然后新建一个对象把日期和原先的数组的内容放进去这里也可以放进去一个当下时间的凌晨的时间戳(后续可以通过这个时间戳比较是否是今天或昨日);然后比较新建的数组中是否有相同的日期,有的话那就将原数组的东西放进去,没有的话那就新建一个对象再放进去。
```<template>
<div></div>
</template>
<script>
import moment from "moment";
export default {
name: "APP",
data() {
return {
list:[1685590792,1685598792,1685590752,1684590792]
};
},
methods: {
sortDate(list) {
let arr = [];
list.forEach((item, index) => {
let tmpDate = new Date(item*1000);
let day = tmpDate.getDate();
let month = tmpDate.getMonth() + 1;
let year = tmpDate.getFullYear();
if (index === 0) {
let tmpObj = {};
tmpObj.date = year + "年" + month + "月" + day + "日";
tmpObj.tmp = moment(tmpDate).startOf("day").valueOf()/1000; //返回当天凌晨的时间戳 可以用于判断是否是当下的今天或昨天的数据
tmpObj.dateList = [];
tmpObj.dateList.push(item);
arr.push(tmpObj);
} else {
if ( arr[arr.length - 1]["date"] === year + "年" + month + "月" + day + "日" ) {
arr[arr.length - 1]["dateList"].push(item);
} else {
let tmpObj = {};
tmpObj.date = year + "年" + month + "月" + day + "日";
tmpObj.tmp = moment(tmpDate).startOf("day").valueOf()/1000;
tmpObj.dateList = [];
tmpObj.dateList.push(item);
arr.push(tmpObj);
}
}
});
return arr;
},
getDate(){
console.log('this.sortDate(list) -----> ', this.sortDate(this.list));
}
},
created() {
this.getDate()
}
};
</script>
<style lang="scss" scoped>
</style>
如果返回的时间戳没有按顺序的,可以这样
<div class="box">
<div
class="list"
v-for="(item,index) in 9"
:key="index"
:class="{checked:checkedIndex===index}"
>
{{index}}
<button v-if="index===4" class="start" @click="running()">开始抽奖</button>
</div>
</div>
</template>
<script>
export default {
name: "APP",
data() {
return {
checkedIndex: "",
currentIndex: "",
timerId: null,
list: [0, 1, 2, 5, 8, 7, 6, 3],
targetIndex: "",
circle: 0
};
},
methods: {
running() {
this.currentIndex = 0;
this.circle++;
clearInterval(this.timerId);
this.timerId = setInterval(() => {
if (this.targetIndex === this.currentIndex && this.circle === 5) {
clearInterval(this.timerId);
this.circle = 0;
console.log("恭喜您中将啦 -----> ");
}
this.checkedIndex = this.list[this.currentIndex];
this.currentIndex++;
if (this.currentIndex >= 8) {
this.running();
}
}, 100 + this.circle * 50);
}
},
created() {
this.targetIndex = Math.floor(Math.random() * 8);
console.log(this.targetIndex);
}
};
</script>
<style scoped>
.box {
width: 610px;
border: 1px solid #000;
margin: 20px auto;
display: flex;
flex-wrap: wrap;
justify-content: space-between;
}
.list {
width: 200px;
height: 200px;
background-color: red;
border: 1px solid #000;
margin-bottom: 1px;
display: flex;
justify-content: center;
align-items: center;
font-size: 40px;
position: relative;
}
.checked {
color: red;
font-size: 60px;
background-color: yellow;
}
.start {
position: absolute;
top: 0;
left: 0;
width: 200px;
height: 200px;
font-size: 40px;
font-weight: 700;
}
.start:hover {
cursor: pointer;
background-color: burlywood;
}
</style>