JavaScript 随机读取数组元素实现

作者:小括号时间:2026-10-29 13:04:47浏览:196

本文介绍在 JavaScript 中随机读取数组元素的方法。通过 Math.random 生成索引,结合 Math.round 取整,实现从数组中随机获取数据。示例代码展示了如何输出随机引用或更新页面元素内容,供开发者参考使用。

JavaScript 随机读取数组元素实现

本文介绍一种在 JavaScript 中随机读取数组元素的具体实现方式,供开发者参考。


function write_quote() {
  var quotes = [
    'no animals were harmed while making this page',
    'made in ulm',
    'this page was handmade',
    'Get <a href="http://www.mozilla.org/products/firefox/">FireFox</a> :-)'
  ];
  var r = Math.round(Math.random() * (quotes.length-1));
  // write the quote
  document.write(quotes[r]);
  // or replace an HTML element:
  // document.getElementById("quote").innerHTML = quotes[r];
}

希望这段代码示例能对您的 JavaScript 开发工作提供帮助。

作者最新文章