JavaScript 从数组中获取随机项程序

要理解此示例,您应了解以下 JavaScript 编程 主题


示例:从数组中获取随机项

// program to get a random item from an array

function getRandomItem(arr) {

    // get random index value
    const randomIndex = Math.floor(Math.random() * arr.length);

    // get random item
    const item = arr[randomIndex];

    return item;
}

const array = [1, 'hello', 5, 8];

const result = getRandomItem(array);
console.log(result);

输出

'hello'

在上面的程序中,通过索引访问了数组中的一个随机项。 数组

  • 使用 Math.random() 方法生成一个介于 0array.length 之间的随机数。
  • Math.floor() 返回由 Math.random() 生成的最近整数值。
  • 然后使用此随机索引来访问数组中的随机元素。

另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战