从JavaScript数组中获取随机值

1233

考虑以下内容:

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

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

28个回答

0

方法1:

  • 使用Math.random()函数获取(0-1,1除外)之间的随机数。
  • 将其乘以数组长度,以获取(0-数组长度)之间的数字。
  • 使用Math.floor()函数获取索引范围从(0到arrayLength-1)。

const arr = ["foo","bar"];
const randomlyPickedString=arr[Math.floor(Math.random() * arr.length)]; console.log(randomlyPickedString);

方法2:

  • random(a, b)方法用于生成数字(a到b,不包括b)之间的随机数。
  • 以floor值来排列数字,将其范围限制在(1到arrayLength)之间。
  • 减去1以获取索引范围从(0到arrayLength-1)。

const arr = ["foo","bar"];
const randomlyPickedString=arr[Math.floor(random(1, 5))-1]; console.log(randomlyPickedString);


0
通过在数组原型上添加一个方法,您可以轻松地获取随机值。
在此示例中,您可以从数组中获取单个或多个随机值。
您可以通过单击片段按钮来运行测试代码。

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


0

寻找真正的一行代码,我找到了这个:

['January', 'February', 'March'].reduce((a, c, i, o) => { return o[Math.floor(Math.random() * Math.floor(o.length))]; })

-1

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

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


-2

这是一个如何实现它的例子:

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

-3

randojs 使这更加简单易读:

console.log( rando(['January', 'February', 'March']).value );
<script src="https://randojs.com/1.0.0.js"></script>


1
有些人不喜欢在库中寻找他们可以自己编写的代码,即使这样做会使事情更快、更易读。如果库因某种原因崩溃,你的网站现在就会出现故障。Randojs不会崩溃,但他们并不知道这一点,因为它不像jQuery这样的库那么出名。 - Aaron Plocharczyk

-3
创建一个随机值并传递给数组
请尝试以下代码...
//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);

6
这个回答使用了与已经被接受的答案相同的解决方案。你应该避免重复添加相同的解决方案,而是仅提出可能的其他选择,这样可以更有助于讨论。 - Pixxl

-7

我真的很惊讶,没有人尝试使用本地随机值:

array[Date.now()%array.length]

它无法处理长度超过160000000000的数组,但我相信你永远不会创建这样的数组

更新

至于你的问题是如何从名为myArray(长度为3)的数组中随机选择值,解决方案应该是:

myArray[Date.now()%myArray.length]

我没有给你的回答点踩,但我不明白你的解决方案与问题有什么关联。我猜其他人也看不出来。 - Manngo
3
@Egor:这些日期值高度确定性,这与随机相反。再说一遍:是的,作为用户,你会感知到随机性,但它与实际的随机性没有任何关系。(顺便说一下:我甚至没有给你投反对票^^) - nuts
2
因为它不是随机的,并且不是一个合适的答案,所以被踩了。 - Brad
4
@Egor,我们真的需要除了显而易见的时间是确定性的证明吗?好吧...在循环中调用它并观察您获得的所有重复值。这是一个不良副作用,在某些时候会咬你一口...如果不是今天,那么将来会咬你一口。这就像,额外输入15个字符才能以正确的方式完成它,有什么关系呢? - Brad
4
@Egor 这个问题是通用的且被引用频繁的。它只是简单地询问如何从数组中获取一个随机值。你的答案没有返回一个随机值。你要求证明你的答案不是随机的。我给了你一个非常清晰和常见的例子来证明它不是随机的。如果你的答案有一些确定性与其他好处的权衡,并且在你的答案中指出了这种权衡,那么就是合适的。相反,你把一个劣质的答案附加到一个十年前的问题上,它没有比已经发布的几个好答案更有优势。因此,我给你点了个踩。 - Brad
显示剩余5条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接