从 JavaScript 数组中获取随机值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4550505/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 12:55:27  来源:igfitidea点击:

Getting a random value from a JavaScript array

javascript

提问by Sarah

Consider:

考虑:

var myArray = ['January', 'February', 'March'];    

How can I select a random value from this array using JavaScript?

如何使用 JavaScript 从这个数组中选择一个随机值?

回答by Jacob Relkin

It is a simple one-liner

这是一个简单的单线

const randomElement = array[Math.floor(Math.random() * array.length)];

Example

例子

const months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
const randomMonth = months[Math.floor(Math.random() * months.length)];

console.log("random month =>", randomMonth);

回答by Brendan Nee

If you've already got underscoreor lodashincluded in your project you can use _.sample.

如果您的项目中已经包含下划线lodash,则可以使用_.sample.

// will return one item randomly from the array
_.sample(['January', 'February', 'March']);

If you need to get more than one item randomly, you can pass that as a second argument in underscore:

如果您需要随机获取多个项目,您可以将其作为下划线中的第二个参数传递:

// will return two items randomly from the array using underscore
_.sample(['January', 'February', 'March'], 2);

or use the _.sampleSizemethod in lodash:

_.sampleSize在 lodash 中使用该方法:

// will return two items randomly from the array using lodash
_.sampleSize(['January', 'February', 'March'], 2);

回答by Ben Aubin

Prototype Method

原型方法

If you plan on getting a random value a lot, you might want to define a function for it.

如果您打算大量获取随机值,则可能需要为其定义一个函数。

First, put this in your code somewhere:

首先,把它放在你的代码中:

Array.prototype.sample = function(){
  return this[Math.floor(Math.random()*this.length)];
}

Now:

现在:

[1,2,3,4].sample() //=> a random element


Code released into the public domain under the terms of the CC0 1.0 license.

根据CC0 1.0 许可条款发布到公共领域的代码。

回答by Ankur Soni

~~is much faster than Math.Floor(), so when it comes to performance optimization while producing output using UI elements, ~~wins the game. MORE INFO

~~比 快得多Math.Floor(),因此在使用 UI 元素生成输出的同时进行性能优化时,~~赢得了比赛。更多信息

var rand = myArray[~~(Math.random() * myArray.length)];

But if you know that the array is going to have millions of elements than you might want to reconsider between Bitwise Operator and Math.Floor(), as bitwise operator behave weirdly with large numbers. See below example explained with the output. MORE INFO

但是,如果您知道数组将有数百万个元素,那么您可能想要在按位运算符和 之间重新考虑Math.Floor(),因为按位运算符在处理大数时表现得很奇怪。请参阅下面的输出示例。更多信息

var number = Math.floor(14444323231.2); // => 14444323231
var number = 14444323231.2 | 0; // => 1559421343

回答by CrazyTim

Say you want to choose a random item that is different from the last time (not really random, but still a common requirement)...

假设您要选择与上次不同的随机项目(不是真正随机,但仍然是一个常见要求)......

Building upon the answer by @Markus, we can add another prototype function:

基于@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];
   }
}

And implement like so:

并像这样实现:

var myRandomDiffElement = myArray.randomDiffElement(lastRandomElement)

回答by I.G. Pascual

If you have fixed values (like a month name list) and want a one-line solution

如果您有固定值(如月份名称列表)并想要单行解决方案

var result = ['January', 'February', 'March'][Math.floor(Math.random() * 3)]

The second part of the array is an access operation as described in Why does [5,6,8,7][1,2] = 8 in JavaScript?

数组的第二部分是访问操作,如在 JavaScript为什么 [5,6,8,7][1,2] = 8?

回答by foxiris

The shortest version:

最短版本:

var myArray = ['January', 'February', 'March']; 
var rand = myArray[(Math.random() * myArray.length) | 0]

回答by Stephan

If you want to write it on one line, like Pascual's solution, another solution would be to write it using ES6's find function (based on the fact, that the probability of randomly selecting one out of nitems is 1/n):

如果你想把它写在一行上,比如 Pascual 的解决方案,另一种解决方案是使用 ES6 的 find 函数编写它(基于事实,从n项目中随机选择一个的概率是1/n):

var item = ['A', 'B', 'C', 'D'].find((_, i, ar) => Math.random() < 1 / (ar.length - i));
console.log(item);

Use that approach for testing purposes and if there is a good reason to not save the array in a seperate variable only. Otherwise the other answers (floor(random()*lengthand using a seperate function) are your way to go.

将该方法用于测试目的,如果有充分的理由不将数组仅保存在单独的变量中。否则其他答案(floor(random()*length并使用单独的函数)是您要走的路。

回答by Nathan

Faker.jshas many utility functions for generating random test data. It is a good option in the context of a test suite:

Faker.js有许多用于生成随机测试数据的实用函数。在测试套件的上下文中,这是一个不错的选择:

const Faker = require('faker');
Faker.random.arrayElement(['January', 'February', 'March']);

As commenters have mentioned, you generally should not use this library in production code.

正如评论者所提到的,您通常不应在生产代码中使用此库。

回答by Seagull

Editing Array prototype can be harmful. Here it is a simple function to do the job.

编辑数组原型可能有害。这是一个简单的功能来完成这项工作。

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
}

Usage:

用法:

// Example 1
var item = getArrayRandomElement(['January', 'February', 'March']);

// Example 2
var myArray = ['January', 'February', 'March'];
var item = getArrayRandomElement(myArray);