Basics:
Copy the array:
(1) Looping traversal copy (not recommended)
The code copy is as follows:
var arr = [1,5,9,7],
new_arry = [],
n = 0,
len = arr.length;
for(;n<len;n++){
new_arry.push(arry[n]);
}
(2) The concat() method is used to concatenate two or more arrays. This method will not change the existing array, but will only return a copy of the connected array.
The code copy is as follows:
var arr = [1,5,9,7],
new_arry = arry.concat();
console.log(new_arry);
(3) The slice() method can return the selected element from the existing array
The code copy is as follows:
var arr = [1,5,9,7],
new_arry = arry.slice(0);
console.log(new_arry);
Random number:
Math.random()
Math.random(), returns a random number from 0 to 1, such as: 0.4261967441998422
Personal encapsulation function:
The code copy is as follows:
function getRandom(opt) {
var old_arry = opt.arry,
range = opt.range;
//Prevent the length of the array from
range = range > old_arry.length?old_arry.length:range;
var newArray = [].concat(old_arry), //Copy the original array and operate it will not destroy 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 then 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 very useful? Very practical code. Here is a separate project from my own project and I hope it will be helpful to you.