如何从给定数字生成随机数

时间:2019-12-24 12:11:08

标签: javascript random numbers

我有一个方案来生成应该从给定数字中生成的随机数。

例如,我有一个数组num = [23,56,12,22]。所以我必须从数组中获取随机数

5 个答案:

答案 0 :(得分:2)

您可以执行以下操作:

function getRandomInt(max) {
  return Math.floor(Math.random() * Math.floor(max));
}

let num=[23,56,12,22];
let randomPosition = getRandomInt(num.length);
console.log(num[randomPosition])

答案 1 :(得分:1)

您可以创建一个返回0到数组长度之间的随机整数的函数,如下所示:

function getRandomInt(max) {
  return Math.floor(Math.random() * Math.floor(max));
}

然后像这样调用它:

let randomInt = getRandonInt(lengthOfArray);

console.log(randomInt);

预期输出:0、1、2 ..数组长度

然后只需使用randomInt从数组条目中获取所需的任何内容即可。

答案 2 :(得分:1)

您可以在0array.length - 1之间生成随机索引

function getRandomInt(max) {
    return Math.floor(Math.random() * Math.floor(max));
}

function getRandomIntFromArray(array) {
    return array[getRandomInt(array.length)]
}

const num = [23,56,12,22]

getRandomIntFromArray(num)

答案 3 :(得分:1)

使用Math.floor(Math.random() * x),其中x是数组的长度,以生成介于0和最大索引之间的随机数

const data = [23,56,12,22]

function randomIndex (array) {
  return array[Math.floor(Math.random() * array.length)];
}

console.log(randomIndex(data));

答案 4 :(得分:0)

如何在间隔[0,len(num)-1]中绘制均匀分布的随机整数,该间隔表示从数组num中绘制的数字的索引。

这是一种非常简单直接的方法。