考虑:

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);

其他回答

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(“项目:”,项目);

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

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

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

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

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

数组的第二部分是一个访问操作,如在JavaScript中为什么[5,6,8,7][1,2]= 8所描述的那样?

获取随机元素的通用方法:

让some_array =[‘简’,2月,3月,4月,“可能”); Let months = random_elems(some_array, 3); console.log(个月); 函数random_elems(arr, count) { 让len = arrr .length; 让查找= {}; Let TMP = []; If (count > len) Count = len; 对于(设I = 0;I < count;我+ +){ 让指数; {做 index = ~~(Math.random() * len); } while(查找中的索引); 查找[index] = null; tmp.push (arr(指数)); } 返回tmp; }

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

var item = ['A', 'B', 'C', 'D']。找到((_,我,ar) = > math . random () < 1 / (ar.length - i)); console.log(项);

如果有充分的理由不将数组保存在单独的变量中,可以将该方法用于测试目的。否则,其他答案(地板(随机()*长度和使用一个单独的函数)是你的方式。