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

如何实现不连续重复的JavaScript随机名言选择器

解决随机名言不连续重复的问题

我来帮你搞定这个问题!核心思路就是记录上一次选中的名言索引,下次随机选择时排除这个索引就行。咱们来修改你的代码:

首先,把名言数组和记录上次索引的变量放到函数外面,避免每次调用start()都重置:

// 把名言数组和上次选中的索引放在全局(或者用闭包,这里先简单用全局)
let quotes = [
  {"content": "Quote #1", "cite": "—Cite #1"},
  {"content": "Quote #2", "cite": "—Cite #2"},
  {"content": "Quote #3", "cite": "—Cite #3"}, // 你原来这里引号打错了,我帮你修正了
  {"content": "Quote #4", "cite": "—Cite #4"}
];
let lastQuoteIndex = -1; // 初始值设为-1,第一次选的时候不会冲突

function start() {
  let randomIndex;
  // 如果名言数量大于1,就确保这次的索引和上次不一样
  if (quotes.length > 1) {
    do {
      randomIndex = Math.floor(Math.random() * quotes.length);
    } while (randomIndex === lastQuoteIndex);
  } else {
    // 只有一条名言的情况,直接选它
    randomIndex = 0;
  }
  
  // 更新上次索引
  lastQuoteIndex = randomIndex;
  // 获取选中的名言
  const selectedQuote = quotes[randomIndex];
  
  // 这里可以添加渲染名言的代码,比如显示到页面上
  console.log(selectedQuote.content, selectedQuote.cite);
  // 示例:假设页面上有id为quoteContent和quoteCite的元素
  // document.getElementById('quoteContent').textContent = selectedQuote.content;
  // document.getElementById('quoteCite').textContent = selectedQuote.cite;
}

关键逻辑说明:

  • lastQuoteIndex:用来存储上一次选中的名言索引,初始值设为-1(因为索引从0开始,第一次选的时候肯定不会重复)。
  • do-while循环:不断生成随机索引,直到生成的索引和上次的不一样,这样就保证了不会连续出现同一条名言。
  • 边界处理:如果名言数组只有一条,直接选它,避免循环无限执行。

另外,我帮你修正了代码里的一个小错误:"Quote #3”这里的右引号是中文的,改成英文双引号了,不然会报错哦。你可以直接调用start()来测试,每次调用都会得到和上次不同的名言啦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:35:37