Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Javascript, how do I generate a random element out of a list?

Suppose I have a list of strings. How do I generate a random one?

like image 338
TIMEX Avatar asked Nov 28 '22 07:11

TIMEX


1 Answers

You mean, get a random array member?

var strings = ['a', 'b', 'c'];

var randomIndex = Math.floor(Math.random() * strings.length);

var randomString = strings[randomIndex];

See it on 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;   
}

See it on jsFiddle.

Of course, you can skip the pool variable and do 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, plus special characters), using a pool is less complex.

like image 181
alex Avatar answered Dec 09 '22 15:12

alex