Copy Code code as follows:
<script language= "JavaScript" >
Returns the NUM non-duplicates randomly from a given array arr
function Getarrayitems (arr, num) {
Creates a new array that copies the incoming array for operations rather than directly manipulating the incoming array;
var temp_array = new Array ();
For (var index in arr) {
Temp_array.push (Arr[index]);
}
The value item that is taken out, saved in this array
var return_array = new Array ();
for (var i = 0; i<num; i++) {
To determine if the array also has elements that can be removed to prevent the subscript from crossing
if (temp_array.length>0) {
Generate a random index in an array
var arrindex = Math.floor (Math.random () *temp_array.length);
Copies the corresponding array element values for this random index
Return_array[i] = Temp_array[arrindex];
Then the array element of this index is deleted, and Temp_array becomes the new array.
Temp_array.splice (Arrindex, 1);
} else {
After the data item in the array is finished, the loop is exited, for example, the array has only 10 entries, but 20 items are required.
Break
}
}
return return_array;
}
Test
var my_array = new Array ();
for (i = 0; i < i++)
{
My_array[i] = "Num:" +i;
}
My_array = Getarrayitems (my_array,5);
for (i = 0; i < my_array.length; i++)
{
Alert (My_array[i]);
}
</script>