I have 100 values in an array but I need to select 5 value randomly on every click one button and I have one value e.g a=10 this a value shouldn't come in the 5 selected value.
I tried in different way but I am not able to do it in j开发者_运维百科query. please any help me.
Dunno, if it strictly needs to be jQuery, but here is a pure JS solution. "input" is the array holding the 100 values.
var output = [];
for (var i = 0, len = input.length; i < 5; ++i) {
var randomIndex = Math.floor(Math.random() * input.length);
if (input[randomIndex] != 10) {
output.push(input[randomIndex);
}
}
The following code may help. The calculateRandoms function calculates 5 different random numbers from the numbers array each time. The random number cannot be value of excludedNumber. You can change randomCount variable to modify the number of random numbers that calculateRandoms will generate.
var excludedNumber = 10;
var randomCount = 5;
var numbers = [];
var randoms = [];
var vPool="";
// initialize array, fill it from 0 to 99
for (var i = 0; i < 100; i++) numbers.push(i + 1);
$(document).ready(function() {
$("#mybutton").click(function() {
calculateRandoms(randomCount);
});
});
function calculateRandoms(c) {
randoms = [];
for (var i = 0; i < c; i++) {
var rnd = excludedNumber;
while (rnd == excludedNumber && $.inArray(rnd, numbers)){
rnd = numbers[Math.floor(Math.random() * numbers.length)];
randoms.push(rnd);
}
}
vPool='';
$.each(randoms, function(i, val) {
vPool+=val + "<br />";
$("#res").html(vPool);
});
//alert(randoms);
//$("#res").html(randoms);
//console.log(randoms);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="button" id="mybutton" value="Generate" />
<div id="res"></div>
You can also resort randomly the original array
function reorder(src) {
return src.sort(function (a, b) { return 1 - (Math.random() * 2); });
}
and you can get the top 5 like this:
yourArray = reorder(yourArray).slice(0, 5);
精彩评论