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

如何用JavaScript从集合中随机选文本?现有代码扩容失效求助

问题:JavaScript随机选取文本集合内容失效问题

我想用JavaScript从一组文本里随机选内容,现在的代码只在4个文本的集合里正常运行,当文本数量增加到8个及以上时就失效了,请协助修改代码以支持更多文本数量,当前代码如下:

原JavaScript代码

var up = document.getElementById('demo');

var safeSet = [
  "https://demo.com/destination-1.html",
  "https://demo.com/destination-2.html",
  "https://demo.com/destination-3.html",
  "https://demo.com/destination-4.html",
  "https://demo.com/destination-5.html",
  "https://demo.com/destination-6.html",
  "https://demo.com/destination-7.html",
  "https://demo.com/destination-8.html"
];

function random(mn, mx) {
  return Math.random() * (mx - mn) + mn;
}

function myFunction() {
  up.innerHTML = safeSet[Math.floor(random(1, 5)) - 1];
}

原HTML代码

<textarea id='demo' type='text'></textarea>
<button onclick="myFunction()">Get Text</button>

修复方案

问题出在myFunction里的random(1, 5)——这个调用固定了随机数范围是1到5,减1后索引只能是0到3,所以不管数组里有多少元素,永远只会选取前4个。要让代码支持任意长度的数组,需要基于数组的动态长度生成随机索引。

修改后的代码如下:

修改后的JavaScript代码

var up = document.getElementById('demo');

var safeSet = [
  "https://demo.com/destination-1.html",
  "https://demo.com/destination-2.html",
  "https://demo.com/destination-3.html",
  "https://demo.com/destination-4.html",
  "https://demo.com/destination-5.html",
  "https://demo.com/destination-6.html",
  "https://demo.com/destination-7.html",
  "https://demo.com/destination-8.html"
];

function myFunction() {
  // 生成0到数组长度-1之间的随机整数索引
  const randomIndex = Math.floor(Math.random() * safeSet.length);
  up.value = safeSet[randomIndex]; // 用value操作textarea内容更规范
}

修改后的HTML代码(无需改动,可直接复用)

<textarea id='demo' type='text'></textarea>
<button onclick="myFunction()">Get Text</button>

关键修改点

  • 移除冗余的自定义random函数,直接通过Math.random() * safeSet.length生成适配数组长度的随机数,再用Math.floor()取整得到合法索引
  • 将up.innerHTML改为up.value,textarea元素的内容操作更推荐使用value属性
  • 现在无论safeSet里有多少元素,都能随机选取到任意一个

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 19:45:42