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)];
}
日志(随机索引(数据))代码>