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

使用innerHTML随机赋值时如何避免出现重复值?

问题原因

你当前的实现每次生成随机索引时,都是从完整的genres数组中取值,没有排除已经被使用过的元素,所以运行时会出现多个按钮内容重复的问题。

解决方案

推荐先打乱数组再按顺序取值,即可保证所有按钮的内容唯一,修改后的JavaScript代码如下:

const genres = ["Crime", "Action", "Drama", "Thriller", "Horror", "Comedy", "History", "Romance", "Adventure", "Epic", "Sci-Fi"];

// 复制原数组并打乱,避免修改原始数据源
const shuffledGenres = [...genres].sort(() => Math.random() - 0.5);
const answers = document.querySelectorAll('.answer');

answers.forEach((answer, index) => {
  answer.innerHTML = shuffledGenres[index];
});

如果对随机结果的均匀性要求更高,可以用标准Fisher-Yates洗牌算法实现数组打乱:

// Fisher-Yates 洗牌算法
function shuffleArray(arr) {
  const array = [...arr];
  for (let i = array.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [array[i], array[j]] = [array[j], array[i]];
  }
  return array;
}

const genres = ["Crime", "Action", "Drama", "Thriller", "Horror", "Comedy", "History", "Romance", "Adventure", "Epic", "Sci-Fi"];
const shuffledGenres = shuffleArray(genres);
const answers = document.querySelectorAll('.answer');

answers.forEach((answer, index) => {
  answer.innerHTML = shuffledGenres[index];
});

上述两种实现都会先把所有可选值打乱,再按按钮数量取前N个值逐个赋值,完全不会出现重复选项的问题。
注意:请保证genres数组的元素数量大于等于按钮的数量,否则会出现取值越界的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 16:06:03