JS method to randomly retrieve several array elements from the array

Source: Internet
Author: User
How does JS randomly retrieve one or several elements from an array? In fact, the method is very simple. Below I will share with you the method of randomly extracting several array elements from JS, which is very good, for more information, see how JS randomly extracts one or several elements from an array.

If the array is

Var items = ['1', '2', '4', '5', '6', '7', '8', '9 ', '10'];

1. Randomly retrieve an element from the array items

Var item = items [Math. floor (Math. random () * items. length)];

2. Randomly retrieve several elements from the previous random array

Function getRandomArrayElements (arr, count) {var shuffled = arr. slice (0), I = arr. length, min = I-count, temp, index; while (I --> min) {index = Math. floor (I + 1) * Math. random (); temp = shuffled [index]; shuffled [index] = shuffled [I]; shuffled [I] = temp;} return shuffled. slice (min);} var items = ['1', '2', '4', '5', '6', '7', '8 ', '9', '10']; console. log (getRandomArrayElements (items, 4 ));

The above section describes how to randomly retrieve several array elements in JS. I hope it will be helpful to you. If you have any questions, please leave a message and I will reply to you in a timely manner. I would like to thank you for your support for PHP chinnet!

For more articles about how to randomly retrieve several array elements from the array by JS, refer to PHP!

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.