+ 1
Como creo un random de string en javascript con funciones?
4 Respostas
0
var cars = ["Saab", "Volvo", "BMW"]; // creas un arreglo de strings
window.alert(cars[Math.floor((Math.random() * 2))]); //número al azar entre 0 y 2 (porque tenemos índices 0, 1 y 2 en nuestro arreglo.
0
(1/2)
Fernando Pozzetti show you a way to select randomly a string from an array (list) of string...
Maybe are you asking for how to generate a string of random chars?
First you must define wich length of string you will generate... it could be randomly too, but you must either define in wich range ^^
var min = ???, max = ???; // max not included
var len = min+Math.floor(Math.random()*(max-min));
Math.floor() truncate (for positive numbers, wich ones we are interesting here) real numbers to their integer part (ie: Math.floor(4.2) => 4).
We use it to get integer, because Math.random() return a real number between 0 and 1 (that's how it works in js).
Then you'll have to initialise a variable fir holding the generated string result to an empty string, loop as many times necessary for getting the targeted string length and append a random char to the string using similar logic than for the random length.
(to be continued -- char limit reached)
0
Roughly, there are two ways to generate random chars:
1) define either an array of chars or a string with the allowed chars to be used in generation (simplest way) and select one by generating randomly their index (min must be 0 and max the "alphabet" string/array length) as we've done for the length.
2) generating char code and convert them to char (1-sized string) value thanks to the String.fromCharCode() static method (but you should be aware some code char range are not "printable" chars).
The former method offer another advantage against the later aside of its root simplicity, to easier let you define highest probability to select some chars than doing the same with the second method, by repeating chars in the "alphabet" (having two "a" and once "b" give 1/3 probability to select "b" against 2/3 to select "a")...
0
Try by yourself: you need to practice for learning ^^
If I do it for you, you will learn nothing ;P