CopyCode The Code is as follows: <script language = "JavaScript">
// Random return of num non-repeated items from a given array arr
Function getarrayitems (ARR, num ){
// Create an array and copy the input array for calculation. Do not directly operate the input array;
VaR temp_array = new array ();
For (VAR index in ARR ){
Temp_array.push (ARR [Index]);
}
// The retrieved value, which is saved in this array
VaR return_array = new array ();
For (VAR I = 0; I <num; I ++ ){
// Determine if the array contains any element that can be retrieved to prevent the subscript from exceeding the limit.
If (temp_array.length> 0 ){
// Generate a random index in the array
VaR arrindex = math. Floor (math. Random () * temp_array.length );
// Copy the array element value corresponding to the random Index
Return_array [I] = temp_array [arrindex];
// Then delete the array element of the index. At this time, temp_array is changed to a new array.
Temp_array.splice (arrindex, 1 );
} Else {
// Exit the loop after the data items in the array are obtained. For example, the array has only 10 items, but 20 items are required.
Break;
}
}
Return return_array;
}
// Test
VaR my_array = new array ();
For (I = 0; I <20; 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>