First, the general algorithm
The first method is more conventional, the test has a bug, the amount of data returned randomly several times after the object directly is a function rather than object. Of course, simple data types should not have this problem.
Sample code
/**
randomly extracts data from the array 2016-09-09
**/
function Getarritem (arr, num) {
var temp_array = new Array ();
For (var index in arr) {
temp_array.push (Arr[index]);
}
var return_array = new Array ();
for (var i = 0; i < num i++) {
if (Temp_array.length > 0) {
var arrindex = Math.floor (Math.random () * tem P_array.length);
Return_array[i] = Temp_array[arrindex];
Temp_array.splice (Arrindex, 1);
} else {break
;
}
}
return return_array;
}
Second, shuffle algorithm
The second is to use the shuffle algorithm, the pro-test effective.
Sample code
/**
Randomized original array
**/
function Shuffle (array) {
var m = array.length,
t, I;
If there are elements
left ... while (m) {
//randomly Select an element ...
i = Math.floor (Math.random () * m--);
Exchange with the current element
t = array[m];
ARRAY[M] = Array[i];
Array[i] = t;
}
return array;
}
Use
var message = Shuffle (Totalarr);
message = Message.slice (0, 3);
The above is for you to sum up the two kinds of JavaScript from the array random out of different elements of the method, I hope this article can be a study or work to bring some help, if you have questions you can message exchange.