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!