This article mainly introduces how to use js to randomly retrieve elements from arrays and share js code encapsulated by individuals. it is very practical. we recommend this article to our partners:
Copy an array:
(1) cyclic traversal replication (not recommended)
The code is as follows:
Var arry = [1, 5, 9, 7],
New_arry = [],
N = 0,
Len = arry. length;
For (; n New_arry.push (arry [n]);
}
(2) the concat () method is used to connect two or more arrays. this method does not change the existing array, but only returns a copy of the connected array.
The code is as follows:
Var arry = [1, 5, 9, 7],
New_arry = arry. concat ();
Console. log (new_arry );
(3) the slice () method returns the selected element from the existing array.
The code is as follows:
Var arry = [1, 5, 9, 7],
New_arry = arry. slice (0 );
Console. log (new_arry );
Random number:
Math. random ()
Math. random () returns a random number ranging from 0 to 1, for example, 0.4261967441998422.
Personal encapsulation functions:
The code is as follows:
Function getRandom (opt ){
Var old_arry = opt. arry,
Range = opt. range;
// Prevent exceeding the length of the array
Range = range> old_arry.length? Old_arry.length: range;
Var newArray = []. concat (old_arry), // copy the original array without damaging the original array
ValArray = [];
For (var n = 0; n <range; n ++ ){
Var r = Math. floor (Math. random () * (newArray. length ));
ValArray. push (newArray [r]);
// Delete the original array and avoid repeated acquisition in the next loop
NewArray. splice (r, 1 );
}
Return valArray;
}
Var new_val = getRandom ({'arry': [1, 6, 8, 0, 3], 'range': 3 });
Console. log (new_val );
Is it easy to use? it is a very practical code. here we will separate it from my project and share it with you. I hope it will help you.