考虑:
var myArray = ['January', 'February', 'March'];
如何使用JavaScript从这个数组中选择一个随机值?
考虑:
var myArray = ['January', 'February', 'March'];
如何使用JavaScript从这个数组中选择一个随机值?
当前回答
方法1:
使用Math.random()函数获取(0- 1,1)之间的随机数 独家)。 将其乘以数组长度得到数字 (0-arrayLength)之间。 使用Math.floor()获取索引范围 从(0到arrayLength-1)。
Const arr = ["foo","bar"]; const randomlyypickedstring =arr[Math.floor(Math.random() * arr.length)]; console.log (randomlyPickedString);
方法2:
random(a, b)方法用于生成(a到b, b不排除)之间的数字。 取下限值,使数字范围从(1到arrayLength)。 减去1得到从(0到arrayLength-1)的下标。
const arr = [“foo”,“bar”]; const randomlyPickedString=arr[Math.floor(random(1, 5))-1]; console.log(randomlyPickedString);
其他回答
我找到了一种方法来解决顶部答案的复杂性,只需将变量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>
这与@Jacob Relkin的解决方案类似,但更普遍:
这是ES2015:
const randomChoice = arr => {
const randIndex = Math.floor(Math.random() * arr.length);
return arr[randIndex];
};
该代码的工作原理是在0到数组长度之间选择一个随机数,然后返回该下标处的项。
Randojs使这更简单和可读:
console.log(rando(['January', 'February', 'March'])。值); < script src = " https://randojs.com/1.0.0.js " > < /脚本>
下面是一个如何做到这一点的例子:
$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)];
最短的版本: var myArray = ['January', 'February', 'March']; var rand = myArray[(Math.random() * myArray.length) | 0] console.log (rand)