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

点击按钮时JS卡片洗牌函数失效问题求助

问题分析与解决

你的洗牌函数(Fisher-Yates算法)本身是正确的,问题出在按钮点击事件的绑定方式上:

当前代码里的这一行:

shuffleButton.onclick = shuffle(cards);

会立即执行shuffle(cards),并把函数执行的结果(洗牌后的数组)赋值给onclick,而不是把函数本身绑定为点击时的回调逻辑。这就导致页面加载时就洗了一次牌,之后点击按钮完全不会触发洗牌操作。

修复方法

把事件绑定改成匿名函数的形式,让点击按钮时才调用洗牌函数:

const shuffleButton = document.querySelector(".shuffleButton");
shuffleButton.onclick = function() {
  shuffle(cards);
  // 这里记得添加洗牌后更新页面卡片的代码,比如重新渲染DOM
};

也可以用更简洁的箭头函数:

shuffleButton.onclick = () => shuffle(cards);

另外补充一点:原洗牌函数会直接修改cards原数组,如果需要保留原始数组的副本,可以在函数里先做拷贝再操作:

function shuffle(array) {
  // 创建数组拷贝,避免修改原数组
  const newArray = [...array];
  let curr = newArray.length, rand;

  while (curr != 0) {
      rand = Math.floor(Math.random() * curr);
      curr--;
      [newArray[curr], newArray[rand]] = [newArray[rand], newArray[curr]];
  }

  return newArray;
}

// 调用时把返回的新数组赋值给cards
shuffleButton.onclick = () => {
  cards = shuffle(cards);
  // 更新DOM展示新的洗牌结果
};

内容的提问来源于stack exchange,提问作者ארי פיין

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 19:42:00