Home  >  Article  >  Web Front-end  >  js implements randomly obtaining elements from an array_javascript skills

js implements randomly obtaining elements from an array_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:20:551153browse

Basic knowledge:

Copy array:

(1) Loop traversal copy (not recommended)

Copy code 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

Copy code The code is as follows:

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

Copy code 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 from 0 to 1, such as: 0.4261967441998422

Personal encapsulation function:

Copy code 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 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.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn