JS gets an array of arbitrary random array elements [original]_javascript tips

Source: Internet
Author: User
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>
Related Article

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.