In Javascript, how do I create a random item from a list?

Suppose I have a list of strings. How to create a random file?

+4
source share
4 answers

Do you mean get a random array?

var strings = ['a', 'b', 'c']; var randomIndex = Math.floor(Math.random() * strings.length); var randomString = strings[randomIndex]; 

Take a look at jsFiddle .

If you mean a random string, it is a little different.

 var randomStrLength = 16, pool = 'abcdefghijklmnopqrstuvwxyz0123456789', randomStr = ''; for (var i = 0; i < randomStrLength; i++) { var randomChar = pool.charAt(Math.floor(Math.random() * pool.length)); randomStr += randomChar; } 

Take a look at jsFiddle .

Of course, you can skip the pool variable and make String.fromCharCode() with a random number between 97 ( 'a'.charCodeAt(0) ) and 122 ( 'z'.charCodeAt(0) ) for lowercase letters, etc. But depending on the range you want (lowercase and uppercase, as well as special characters), using the pool is less complicated.

+21
source

Alex and Mahesh on the right track, just wanted to demonstrate how I could implement their decisions if I felt dangerous. What am I doing.

 Array.prototype.chooseRandom = function() { return this[Math.floor(Math.random() * this.length)]; }; var a = [1, 2, 3, 4, 5]; a.chooseRandom(); // => 2 a.chooseRandom(); // => 1 a.chooseRandom(); // => 5 
+8
source
 var randomString = myStrings[Math.floor(Math.random() * myStrings.length)] 
+2
source
 var rand = 0; var newPic = []; var pic = [1,2,3] //length = 18 for ( var i=0; i<18; i++ ){ rand = Math.floor(Math.random()*19); newPic.push(pic[rand-1].slice()); } alert(newPic); 
0
source

Source: https://habr.com/ru/post/1332050/


All Articles