You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript洗牌按钮点击计数器功能实现求助

实现洗牌点击计数器功能

按照你的需求,我们可以分几步把计数器功能整合到现有代码里,逻辑非常清晰:

步骤1:添加计数器显示元素

先在HTML里加个显示点击次数的区域,放在按钮上方即可:

<p>洗牌次数: <span id="shuffleCount">0</span></p>

步骤2:初始化计数器变量与更新函数

在JS代码最开头,声明全局计数器变量,再写一个专门更新页面显示的小函数,避免重复代码:

// 初始化计数器为0
let shuffleCount = 0;

// 更新页面上的计数器显示
function updateCountDisplay() {
  document.getElementById("shuffleCount").textContent = shuffleCount;
}

步骤3:修改洗牌函数

每次点击Shuffle按钮时,让计数器加1,然后调用更新函数同步页面显示:

function shuffle() {
  shuffleCount++; // 点击一次计数+1
  updateCountDisplay(); // 更新页面显示
  
  const copiedArr = array.map(n => n);
  const shuffledArray = shuffleArray(copiedArr);
  document.getElementById("array").innerText = printArray(shuffledArray);
}

步骤4:修改重置函数

点击Restore按钮时,把计数器清零并同步页面显示:

function restore() {
  shuffleCount = 0; // 重置计数器
  updateCountDisplay(); // 更新页面显示
  
  document.getElementById("array").innerText = printArray(array);
}

完整代码示例

修改后的HTML

<div class="container">
  <span id="array"><pre></pre></span>
</div>
<br>
<p>洗牌次数: <span id="shuffleCount">0</span></p>
<br>
<button onclick="shuffle()" value="randomize">Shuffle!</button>
<button onclick="restore()">Restore</button>

修改后的JS

let shuffleCount = 0;

function updateCountDisplay() {
  document.getElementById("shuffleCount").textContent = shuffleCount;
}

function shuffleArray(arr) {
  for (let i = arr.length - 1; i > 0; i--) {
    const r = Math.floor(Math.random() * (i + 1));
    [arr[i], arr[r]] = [arr[r], arr[i]];
  }
  return arr;
};

const array = ["Apple", "Pear", "Apricot", "Nashy", "Kiwi", "Watermelon"];

function printArray(arr) {
  return arr.reduce((acc, n, i) => {
    return acc.concat(i < arr.length - 1 ? `${n}\n ` : `${n}`);
  }, '');
};

function shuffle() {
  shuffleCount++;
  updateCountDisplay();
  
  const copiedArr = array.map(n => n);
  const shuffledArray = shuffleArray(copiedArr);
  document.getElementById("array").innerText = printArray(shuffledArray);
}

function restore() {
  shuffleCount = 0;
  updateCountDisplay();
  
  document.getElementById("array").innerText = printArray(array);
}

// 初始化页面显示
restore();
updateCountDisplay();

关于页面刷新或离开的情况:因为计数器是存储在浏览器内存中的,刷新页面或关闭页面后,浏览器会自动清空这些临时变量,所以计数器会自动重置为0,不需要额外写代码处理。

内容的提问来源于stack exchange,提问作者DadManOZ

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 20:15:55