考虑以下内容:
var myArray = ['January', 'February', 'March'];
如何使用JavaScript从该数组中随机选择一个值?
考虑以下内容:
var myArray = ['January', 'February', 'March'];
如何使用JavaScript从该数组中随机选择一个值?
方法1:
const arr = ["foo","bar"];
const randomlyPickedString=arr[Math.floor(Math.random() * arr.length)]; console.log(randomlyPickedString);
方法2:
const arr = ["foo","bar"];
const randomlyPickedString=arr[Math.floor(random(1, 5))-1]; console.log(randomlyPickedString);
Array.prototype.random = function(n){
if(n&&n>1){
const a = [];
for(let i = 0;i<n;i++){
a.push(this[Math.floor(Math.random()*this.length)]);
}
return a;
} else {
return this[Math.floor(Math.random()*this.length)];
}
}
const mySampleArray = ['a','b','c','d','e','f','g','h'];
mySampleArray.random(); // return any random value etc. 'a', 'b'
mySampleArray.random(3); //retun an array with random values etc: ['b','f','a'] , ['d','b','d']
alert(mySampleArray.random());
alert(mySampleArray.random(3));
寻找真正的一行代码,我找到了这个:
['January', 'February', 'March'].reduce((a, c, i, o) => { return o[Math.floor(Math.random() * Math.floor(o.length))]; })
获取随机元素的通用方法:
let some_array = ['Jan', 'Feb', 'Mar', 'Apr', 'May'];
let months = random_elems(some_array, 3);
console.log(months);
function random_elems(arr, count) {
let len = arr.length;
let lookup = {};
let tmp = [];
if (count > len)
count = len;
for (let i = 0; i < count; i++) {
let index;
do {
index = ~~(Math.random() * len);
} while (index in lookup);
lookup[index] = null;
tmp.push(arr[index]);
}
return tmp;
}
这是一个如何实现它的例子:
$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)];
randojs 使这更加简单易读:
console.log( rando(['January', 'February', 'March']).value );
<script src="https://randojs.com/1.0.0.js"></script>
//For Search textbox random value
var myPlaceHolderArray = ['Hotels in New York...', 'Hotels in San Francisco...', 'Hotels Near Disney World...', 'Hotels in Atlanta...'];
var rand = Math.floor(Math.random() * myPlaceHolderArray.length);
var Placeholdervalue = myPlaceHolderArray[rand];
alert(Placeholdervalue);
我真的很惊讶,没有人尝试使用本地随机值:
array[Date.now()%array.length]
它无法处理长度超过160000000000的数组,但我相信你永远不会创建这样的数组
更新
至于你的问题是如何从名为myArray
(长度为3)的数组中随机选择值,解决方案应该是:
myArray[Date.now()%myArray.length]