1.按钮倒计时
<button id="btn1">获取验证码</button>
在做一个动态效果的时候,事件里面的定时器应先清除在设置,防止多次点击直接生成多个定时器,所以每生成一次事件需要清除一次定时器,达到始终保持事件里只有一个定时器。定时器起在一个事件里执行完毕时清除的作用。
<script>
var btn1=document.getElementById('btn1')
function clickbtn(){
var time=5
var timer=setInterval(function(){
btn1.disabled=true;
time--;
if(time>0){
btn1.innerHTML='倒计时'+'('+time+')'+'获取验证码'
}
if(time==0){
clearInterval(timer)//清除定时器
btn1.innerHTML='获取验证码'
btn1.disabled=false;
}
},1000)
}
btn1.addEventListener('click',function(){
clickbtn()
})
</script>
2.去重排序
已知 list 数组请写出一段代码,实现功能: 数组内type 相同的元素只保留 votes 最大的元素,并且元素需要按照 votes 从大到小排序。
<script>
var list = [
{type: 1, des: "dddd", votes: 80},
{type: 2, des: "dddd", votes: 60},
{type: 3, des: "dddd", votes: 70},
{type: 1, des: "dddd", votes: 50},
{type: 3, des: "dddd", votes: 80},
{type: 8, des: "dddd", votes: 80},
{type: 9, des: "dddd", votes: 20},
{type: 1, des: "dddd", votes: 100},
{type: 3, des: "dddd", votes: 30}
];
// 创建对象存储每种类型的最大投票数
var maxVotes = {};
list.forEach(function(item) {
if (!maxVotes[item.type] || item.votes > maxVotes[item.type]) {
maxVotes[item.type] = item.votes;
}
});
// 过滤数组,只保留每种类型的最大投票数
var filteredList = list.filter(function(item) {
return item.votes === maxVotes[item.type];
});
// 按照投票数从大到小排序
filteredList.sort(function(a, b) {
return b.votes - a.votes;
});
console.log(maxVotes);
console.log(filteredList);
</script>