最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to pick random number of items randomly in an array - Stack Overflow

programmeradmin2浏览0评论

I want to pick random number of inputs randomly in an array of input elements..
If i use the below method i Can get one random item

jQuery.jQueryRandom = 0;
jQuery.extend(jQuery.expr[":"],
 {
  random: function(a, i, m, r) {
    if (i == 0) {
        jQuery.jQueryRandom = Math.floor(Math.random() * r.length);
    };
    return i == jQuery.jQueryRandom;
 }
});

$("input:random").prop('id')

But I want random number i=of items to be picked randomly in an array.

I want to pick random number of inputs randomly in an array of input elements..
If i use the below method i Can get one random item

jQuery.jQueryRandom = 0;
jQuery.extend(jQuery.expr[":"],
 {
  random: function(a, i, m, r) {
    if (i == 0) {
        jQuery.jQueryRandom = Math.floor(Math.random() * r.length);
    };
    return i == jQuery.jQueryRandom;
 }
});

$("input:random").prop('id')

But I want random number i=of items to be picked randomly in an array.

Share Improve this question asked Nov 29, 2011 at 8:31 ExceptionException 8,38924 gold badges88 silver badges141 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 7

You can use jQuery's .filter() method with a function:

$('div').filter(function(){
    return (Math.round(Math.random()) == 1);
}).css({background: 'red'});

jsFiddle example

You currently are checking if the index is equal to the random number. Maybe it´s better to generate a random number for each input and check if its bigger then 1 or smaller. So randomize a number between 0 and 2. something like:

jQuery.extend(jQuery.expr[":"],
 {
  random: function(a, i, m, r) {
    return Math.random() > 0.5;
 }
});

alert( $("input:random").length );

Also if you get a prop from an element, it will only get it from the first one.

I'm proposing a non-jQuery answer to you question on how to get count elements randomly from an array arr

var pickRandom = function (arr, count) {
  var out = [], i, pick, clone = arr.slice(0, arr.length);
  for (i = 0; i < count; i ++) {
    pick = Math.floor(Math.random() * clone.length);
    if (clone[pick] !== undefined) {
      out.push(clone[pick]);
      clone.splice(pick, 1);
    }
  }
  return out;
};

This function makes sure that the original array is preserved and handles undefined values correctly

发布评论

评论列表(0)

  1. 暂无评论