Basic knowledge:
Copy array:
(1) Loop traversal copy (not recommended)
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
var arry = [1,5,9,7],
new_arry = arry.concat();
console.log(new_arry);
(3) The slice() method can return selected elements from an existing array
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 from 0 to 1, such as: 0.4261967441998422
Personal encapsulation function:
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 for operation without destroying the original array
valArray = [];
for (var n = 0; n < range; n ) {
var r = Math.floor(Math.random() * (newArray.length));
valArray.push(newArray[r]);
//Delete it in the original array, and then avoid repeated acquisition in the next cycle
newArray.splice(r, 1);
}
Return valArray;
}
var new_val = getRandom({'arry':[1,6,8,0,3],'range':3});
console.log(new_val);
Isn’t it very useful? It’s a very practical code. Here it is separated from my project and shared with everyone. I hope it will be helpful to everyone.