使用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
相关产品推荐
相关产品推荐

