简体   繁体   English

Javascript:从数组中选择不等于“ undefined”的随机元素

[英]Javascript: select random element from array that is not equal to 'undefined'

I have an array that has only had specific keys set. 我有一个只设置了特定键的数组。 The array will look something like 数组看起来像

arr[0] = 'undefined';
arr[1] = '16';
arr[2] = 'undefined';
arr[3] = '13';
arr[4] = 'undefined';
arr[5] = 'undefined';
arr[6] = '24';
arr[7] = 'undefined';

From that particular array I would want to randomly select either 16, 13, or 24. 我想从该特定数组中随机选择16、13或24。

Is there a good way to do this? 有什么好方法吗?

Thanks, 谢谢,
Sam 山姆

Make a new array consisting of the indexes of the entries of your original array that you wish to consider (eg {1, 3, 5} in your case); 创建一个新数组,该数组由您要考虑的原始数组的条目的索引组成(例如, {1, 3, 5} ); then pick a random element (in whichever way that satisfies your statistical requirements) from the index array and then retrieve the corresponding value. 然后从索引数组中选择一个随机元素(以任何满足您的统计要求的方式),然后检索相应的值。

First I would loop through the array stripping out the undefined values. 首先,我将遍历数组以除去undefined值。 Then pick an element from the resulting array. 然后从结果数组中选择一个元素。

The 'best' way of doing this would be to randomly select one element in a loop. 做到这一点的“最佳”方法是在循环中随机选择一个元素。 Exit the loop if the selected element is not "undefined". 如果所选元素不是“未定义”,则退出循环。

\n
\n
\n
arr = arr.filter(function (n) { return n !== undefined });
\n
\n
\n

function randomFromTo(from, to){
    return Math.floor(Math.random() * (to - from + 1) + from);
}

var Arr = // You define this
var answer = 'undefined';
while (answer == 'undefined'){
     answer = Arr[randomFromTo(0, Arr.length)];
}

Thanks to http://www.admixweb.com/2010/08/24/javascript-tip-get-a-random-number-between-two-integers/ 感谢http://www.admixweb.com/2010/08/24/javascript-tip-get-a-random-number-between-two-integers/

(function( src ) {
    console.log( src[ ~~(Math.random() * src.length) ] );
}( arr.filter(function( elem ) { return elem !== 'undefined'; }) ));

Demo: http://jsfiddle.net/y7g6x/ 演示: http//jsfiddle.net/y7g6x/

This is slightly tricky. 这有点棘手。 What basically happens is, that the array is first filtered for all non 'undefined' values. 基本上发生的是,首先针对所有非“未定义”值过滤数组。 That new array is then passed into the self-invoking function where we just call a console.log() on a random element. 然后,该新数组将传递到自调用函数中,在该函数中,我们仅在随机元素上调用console.log() We need to make sure that our call to Math.random() does not deliver some floating point value, so I'm using ~~ to cut numbers. 我们需要确保对Math.random()调用不会传递一些浮点值,因此我正在使用~~削减数字。 Its probably more convinient to use Math.floor() there. 在此处使用Math.floor()可能更方便。

Randomly select one index and from that index search for a non-undefined element. 随机选择一个索引,然后从该索引中搜索一个未定义的元素。

function getrandom(arr){
    var ri = Math.floor(Math.random() * arr.length);

    for(var i=0; i<arr.length; i++){
      var ai = (i + ri)%arr.length;
      if(arr[ai] != 'undefined'){
         return arr[ai];
     }
   }
}

Here's a way that is unbiased, doesn't create a temporary array and only scans the array once. 这是一种没有偏见的方法,不会创建临时数组,而只会扫描一次数组。 It's based on reservoir sampling . 它基于储层采样

function pick_random_value(src)
  local count = 0
  local value = undefined
  for( i=0; i<src.length; ++i)
  {
    if (src[i]==='undefined') { continue; }
    ++count;
    if ( Math.random() < 1/count ) { value = src[i]; }
  }
  return value;
end

The downside is that Math.random() gets called multiple times. 缺点是Math.random()被多次调用。 There may be ways to reduce that number of calls though. 不过,可能有一些方法可以减少该数量的电话。

An upside is that it can be modified to select N unique items rather than just one easily. 一个好处是,可以对其进行修改以选择N个唯一项,而不仅仅是一项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM