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;
}
// will return two items randomly from the array using lodash
_.sampleSize(['January', 'February', 'March'], 2);
3
假设您要选择与上次不同的随机项目(不是非常随机,但仍然是常见要求)...
在@Markus的答案基础上,我们可以添加另一个原型函数:
Array.prototype.randomDiffElement = function(last) {
if (this.length == 0) {
return;
} else if (this.length == 1) {
return this[0];
} else {
var num = 0;
do {
num = Math.floor(Math.random() * this.length);
} while (this[num] == last);
return this[num];
}
}
并执行如下:
var myRandomDiffElement = myArray.randomDiffElement(lastRandomElement)
0
编辑阵列原型可能是有害的 . 这是一个简单的功能来完成这项工作 .
function getArrayRandomElement (arr) {
if (arr && arr.length) {
return arr[Math.floor(Math.random() * arr.length)];
}
// The undefined will be returned if the empty array was passed
}
用法:
// Example 1
var item = getArrayRandomElement(['January', 'February', 'March']);
// Example 2
var myArray = ['January', 'February', 'March'];
var item = getArrayRandomElement(myArray);
//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);
for (var prop in myArray) {
if (myArray.hasOwnProperty(prop)) {
...
}
}
(这对你来说可能是麻烦,也可能不是麻烦 . )
1
最短的版本:
var myArray = ['January', 'February', 'March'];
var rand = myArray[(Math.random() * myArray.length) | 0]
1
var item = myArray[Math.floor(Math.random()*myArray.length)];
或等效的较短版本:
var item = myArray[(Math.random()*myArray.length)|0];
示例代码:
var myArray = ['January', 'February', 'March'];
var item = myArray[(Math.random()*myArray.length)|0];
console.log('item:', item);
-1
var rand = myArray[Math.floor(Math.random() * myArray.length)];
18
以下是如何执行此操作的示例:
$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)];
2
简单功能:
var myArray = ['January', 'February', 'March'];
function random(array) {
return array[Math.floor(Math.random() * array.length)]
}
random(myArray);
要么
var myArray = ['January', 'February', 'March'];
function random() {
return myArray[Math.floor(Math.random() * myArray.length)]
}
random();
要么
var myArray = ['January', 'February', 'March'];
function random() {
return myArray[Math.floor(Math.random() * myArray.length)]
}
random();
23 回答
获取随机元素的通用方法:
如果您的项目中已包含underscore或lodash,则可以使用_.sample .
如果您需要随机获得多个项目,可以将其作为下划线中的第二个参数传递:
或者在lodash中使用_.sampleSize方法:
假设您要选择与上次不同的随机项目(不是非常随机,但仍然是常见要求)...
在@Markus的答案基础上,我们可以添加另一个原型函数:
并执行如下:
编辑阵列原型可能是有害的 . 这是一个简单的功能来完成这项工作 .
用法:
您为数组设置了一个常量变量,然后您有另一个在数组中的三个对象之间随机选择的常量,然后该函数只返回结果 .
~~
比Math.Floor()
快得多,因此在使用UI元素生成输出时进行性能优化时,~~
赢得游戏 . MORE INFO但是如果你知道数组将有比你想要在Bitwise运算符和
Math.Floor()
之间重新考虑的数百万个元素一样,那么按位运算符的行为就像大数字一样奇怪 . 请参阅以下使用输出解释的示例 . MORE INFO使用Faker.js:
我已经找到了绕过最佳答案的复杂方法,只需将变量rand连接到另一个变量,该变量允许在调用myArray [];内部显示该数字 . 通过删除创建的新阵列并解决其中的复杂问题,我提出了一个可行的解决方案:
这项工作对我而言毫无重复的魅力 .
创建一个随机值并传递给数组
请尝试以下代码..
递归,独立函数,可以返回任意数量的项目(与lodash.sampleSize相同):
原型方法
如果您计划大量获取随机值,则可能需要为其定义函数 .
首先,将它放在代码中的某处:
现在:
代码根据CC0 1.0 license条款发布到公共领域 .
如果您有固定值(如月份名称列表)并想要一个单行解决方案
数组的第二部分是Why does [5,6,8,7][1,2] = 8 in JavaScript?中描述的访问操作
如果你想在一行上写它,比如Pascual 's solution, another solution would be to write it using ES6' s find函数(根据事实,随机选择
n
项中的一个的概率是1/n
):使用该方法进行测试,如果有充分的理由不将数组保存在单独的变量中 . 否则,其他答案(
floor(random()*length
并使用单独的功能)是你的方法 .这与@Jacob Relkin的解决方案类似,但更为通用:
这是ES2015:
该代码通过选择0和数组长度之间的随机数,然后返回该索引处的项目来工作 .
在我看来,更好地搞乱原型,或者及时宣布原型,我更喜欢将它暴露在窗口中:
现在你的应用程序的任何地方都称它为:
这样你仍然可以正确使用
for(x in array)
循环我发现将原型函数添加到Array类更简单:
现在我只需键入以下内容即可获得随机数组元素:
请注意,这将向所有数组添加属性,因此如果使用
for..in
循环使用.hasOwnProperty()
,则应使用.hasOwnProperty()
:(这对你来说可能是麻烦,也可能不是麻烦 . )
最短的版本:
var item = myArray[Math.floor(Math.random()*myArray.length)];
或等效的较短版本:
var item = myArray[(Math.random()*myArray.length)|0];
示例代码:
以下是如何执行此操作的示例:
简单功能:
要么
要么