Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/368.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何从给定的数字生成随机数_Javascript_Random_Numbers - Fatal编程技术网

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

Javascript 如何从给定的数字生成随机数,javascript,random,numbers,Javascript,Random,Numbers,我有一个生成随机数的场景,应该从给定的数字生成随机数 例如,我有一个数组num=[23,56,12,22]。因此,我必须从数组中获取随机数在区间[0,len(num)-1]中绘制一个均匀分布的随机整数,它表示从数组中绘制的数字的索引 这是一种非常简单直接的方法。您可以这样做: function getRandomInt(max) { return Math.floor(Math.random() * Math.floor(max)); } let randomInt = getRandon

我有一个生成随机数的场景,应该从给定的数字生成随机数


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

在区间
[0,len(num)-1]
中绘制一个均匀分布的随机整数,它表示从数组中绘制的数字的索引


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

您可以这样做:

function getRandomInt(max) {
  return Math.floor(Math.random() * Math.floor(max));
}
let randomInt = getRandonInt(lengthOfArray);

console.log(randomInt);
函数getRandomInt(最大值){
返回Math.floor(Math.random()*Math.floor(max));
}
设num=[23,56,12,22];
设randomPosition=getRandomInt(num.length);

log(num[randomPosition])
您可以创建一个函数,返回一个介于0和数组长度之间的随机整数,如下所示:

function getRandomInt(max) {
  return Math.floor(Math.random() * Math.floor(max));
}
let randomInt = getRandonInt(lengthOfArray);

console.log(randomInt);
那么就这样称呼它:

function getRandomInt(max) {
  return Math.floor(Math.random() * Math.floor(max));
}
let randomInt = getRandonInt(lengthOfArray);

console.log(randomInt);
预期输出:0、1、2。。数组长度


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

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

函数getRandomInt(最大值){
返回Math.floor(Math.random()*Math.floor(max));
}
函数getRandomIntFromArray(数组){
返回数组[getRandomInt(array.length)]
}
const num=[23,56,12,22]
getRandomIntFromArray(num)
使用
Math.floor(Math.random()*x)
,其中x是数组的长度,用于生成介于0和最大索引之间的随机数

const data=[23,56,12,22]
函数索引(数组){
返回数组[Math.floor(Math.random()*array.length)];
}
日志(随机索引(数据))