Could someone explain to me how this function works?
var randomize = function(length){
var text = "";
var possible = "123abc";
for (var i = 0 ; i < length; i++)
text += possible.charAt(Math.floor(Math.random()*possible.length))
return text;
}
console.log(randomize(6));
I'm trying to understand it but some lines don't make sense.
possible
- list of characters to choose from
Math.random()
returns a float number between 0 (inclusive) and 1 (exclusive)
Math.random()*possible.length
makes it a float number between 0 and possible.length
Math.floor(Math.random()*possible.length)
makes it an integer between 0 (inclusive) and possible.length
(exclusive)
possible.charAt(position_here)
takes a character at position position_here
from the string possible
(0-indexed)
text += something_here
is the same as text = text + something_here
. Append another string (in this case: character) to already existing value of text.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.