Two ways for JavaScript to randomly extract different elements from an array _javascript techniques

Source: Internet
Author: User
Tags shuffle

First, the general algorithm

The first method is more conventional, the test has a bug, the amount of data returned randomly several times after the object directly is a function rather than object. Of course, simple data types should not have this problem.

Sample code

     randomly extracts data from the array 2016-09-09
   function Getarritem (arr, num) {
     var temp_array = new Array ();
     For (var index in arr) {
       temp_array.push (Arr[index]);
     var return_array = new Array ();
     for (var i = 0; i < num i++) {
       if (Temp_array.length > 0) {
         var arrindex = Math.floor (Math.random () * tem P_array.length);
         Return_array[i] = Temp_array[arrindex];
         Temp_array.splice (Arrindex, 1);
       } else {break
     return return_array;

Second, shuffle algorithm

The second is to use the shuffle algorithm, the pro-test effective.

Sample code

      Randomized original array
    function Shuffle (array) {
      var m = array.length,
        t, I;
      If there are elements
      left ... while (m) {
        //randomly Select an element ...
        i = Math.floor (Math.random () * m--);
        Exchange with the current element
        t = array[m];
        ARRAY[M] = Array[i];
        Array[i] = t;
      return array;
var message = Shuffle (Totalarr);
message = Message.slice (0, 3);

The above is for you to sum up the two kinds of JavaScript from the array random out of different elements of the method, I hope this article can be a study or work to bring some help, if you have questions you can message exchange.

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: 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.