考虑:
var myArray = ['January', 'February', 'March'];
如何使用JavaScript从这个数组中选择一个随机值?
考虑:
var myArray = ['January', 'February', 'March'];
如何使用JavaScript从这个数组中选择一个随机值?
当前回答
您可以考虑在Array原型上定义一个函数,以便创建一个返回随机元素的方法[].sample()。
首先,要定义原型函数,将以下代码片段放入代码中:
Array.prototype.sample = function(){
return this[Math.floor(Math.random()*this.length)];
}
之后,要从数组中随机抽取一个元素,只需调用.sample():
[1,2,3,4].sample() //=> a random element
我将根据CC0 1.0许可证的条款将这些代码片段发布到公共领域。
其他回答
我找到了一种方法来解决顶部答案的复杂性,只需将变量rand连接到另一个变量,允许该数字在myArray[];的调用中显示。通过删除创建的新数组并处理它的复杂性,我提出了一个可行的解决方案:
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var myArray = ['January', 'February', 'March', 'April', 'May'];
var rand = Math.floor(Math.random() * myArray.length);
var concat = myArray[rand];
function random() {
document.getElementById("demo").innerHTML = (concat);
}
</script>
<button onClick="random();">
Working Random Array generator
</button>
</body>
</html>
下面是一个如何做到这一点的例子:
$scope.ctx.skills = data.result.skills;
$scope.praiseTextArray = [
"Hooray",
"You\'re ready to move to a new skill",
"Yahoo! You completed a problem",
"You\'re doing great",
"You succeeded",
"That was a brave effort trying new problems",
"Your brain was working hard",
"All your hard work is paying off",
"Very nice job!, Let\'s see what you can do next",
"Well done",
"That was excellent work",
"Awesome job",
"You must feel good about doing such a great job",
"Right on",
"Great thinking",
"Wonderful work",
"You were right on top of that one",
"Beautiful job",
"Way to go",
"Sensational effort"
];
$scope.praiseTextWord = $scope.praiseTextArray[Math.floor(Math.random()*$scope.praiseTextArray.length)];
static generateMonth() { const theDate = ['January', 'February', 'March']; const randomNumber = Math.floor(Math.random()*3); 返回theDate [randomNumber]; };
在数组中设置一个常量变量,然后在数组中的三个对象中随机选择另一个常量,然后函数简单地返回结果。
这是一个简单的一行代码:
const randomElement = array[Math.floor(Math.random() * array.length)];
例如:
const月=(“1”,“2”,“3”、“4”,“可能”,“6”,“7”); const random = Math.floor(Math.random() * months.length); console.log(随机、几个月(随机));
递归的独立函数,可以返回任意数量的项(与lodash.sampleSize相同):
function getRandomElementsFromArray(array, numberOfRandomElementsToExtract = 1) {
const elements = [];
function getRandomElement(arr) {
if (elements.length < numberOfRandomElementsToExtract) {
const index = Math.floor(Math.random() * arr.length)
const element = arr.splice(index, 1)[0];
elements.push(element)
return getRandomElement(arr)
} else {
return elements
}
}
return getRandomElement([...array])
}