JS randomly retrieves N non-duplicated data from the specified array.

Source: Internet
Author: User

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>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.