You need to enable JavaScript to run this app. 如何用JS实现页面加载时随机选取3条不重复评价渲染到指定DOM元素
优惠活动
大模型
产品
解决方案
定价
更多

如何用JS实现页面加载时随机选取3条不重复评价渲染到指定DOM元素

现有代码的可修正问题
  • 拼写错误:JS 对大小写敏感,代码中多次将Math.floor写为首字母大写的Math.Floor,执行时会直接抛出引用错误,导致随机逻辑无法运行
  • 缺失去重逻辑:三次独立生成随机下标的方式,存在生成相同数值的概率,会出现同一条评价被重复展示的问题
  • 渲染逻辑偏差:当前代码向DOM写入的是随机生成的下标数字,没有通过下标读取reviews数组中对应的评价内容,页面会直接显示数字而非评价文本
无重复随机选取的实现方法

要实现不重复选取3条评价的效果,最稳定的方案是通过Fisher-Yates洗牌算法打乱评价数组的顺序,再直接截取前3条写入对应DOM节点:

  • 打乱操作基于数组副本执行,不会修改原始评价数据
  • 天然保证选中内容互不重复,后续扩充评价库时不需要调整选取逻辑
  • 不需要写复杂的下标比对去重代码,维护成本更低
优化后的完整可运行代码
const reviews = [
  "Thank you Anne for fitting me in yesterday when you realised I was desperate to get the house cleaned before the blinds and curtains were fitted. Marie and Michaela did a great job, leaving it sparkling clean. I will certainly recommend you to anyone who needs a cleaner. That you are so approachable, helpful and friendly is a bonus. - <strong>Rosemary OBoyle</strong>",
  "Great job on all the awkward hate to do Jobs! Came home from my holidays and my house was sparkling, highly recommended!! - <strong>Lynne Gardiner</strong>",
  "Domestic Angels are angels to me, just left lovely Kelly cleaning my house in preparation for mums arrival, while I chill at hairdressers, thank you to Anne & her team, can't recommend them enough - <strong>Julie Magee</strong>"
]

// Fisher-Yates 数组打乱实现
function shuffleArray(arr) {
  const tempArr = [...arr]
  for (let i = tempArr.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [tempArr[i], tempArr[j]] = [tempArr[j], tempArr[i]]
  }
  return tempArr
}

function renderRandomReviews() {
  // 打乱后截取前3条评价
  const selectedReviews = shuffleArray(reviews).slice(0, 3)
  // 依次写入对应DOM节点
  document.getElementById("review-1").innerHTML = selectedReviews[0]
  document.getElementById("review-2").innerHTML = selectedReviews[1]
  document.getElementById("review-3").innerHTML = selectedReviews[2]
}

// 页面加载完成后触发渲染
window.addEventListener('load', renderRandomReviews)

适配说明:后续新增评价只需要往reviews数组中追加内容即可,不需要修改选取、渲染的核心逻辑。如果后续可能出现评价总数不足3条的情况,可在截取操作后增加判断逻辑做兜底提示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.29 21:15:03