How does js randomly take one element or several elements from an array?Actually the method is very simple,Below we share with you the method of randomly taking out a few array elements by js,very good,

How does js randomly take one or several elements from an array.

If the array is

var items=["1", "2", "4", "5", "6", "7", "8", "9", "10"];

1. Randomly take an element from the array items

var item=items [math.floor (math.random () * items.length)];

2. Randomly take a few 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;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));
  • Previous JS example code for judging input string length (Chinese characters count as two characters, alphanumeric count as one)
  • Next AngularJS basic ng-list instructions and sample code