Copy codeThe 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 ArrList = [, 33];
Alert (getArrayItems (ArrList, 6 ));
</Script>