简体   繁体   English

谁能解释这个功能

[英]can someone explain this function

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 possible - 可供选择的字符列表

Math.random() returns a float number between 0 (inclusive) and 1 (exclusive) Math.random()返回0(包括)和1(不包括)之间的浮点数

Math.random()*possible.length makes it a float number between 0 and possible.length Math.random()*possible.length使它成为0和possible.length之间的浮点数

Math.floor(Math.random()*possible.length) makes it an integer between 0 (inclusive) and possible.length (exclusive) Math.floor(Math.random()*possible.length)使它成为0(包括)和possible.length (不包括)之间的整数

possible.charAt(position_here) takes a character at position position_here from the string possible (0-indexed) possible.charAt(position_here)需要一个字符在位置position_here从字符串possible (0索引)

text += something_here is the same as text = text + something_here . text += something_heretext = text + something_here Append another string (in this case: character) to already existing value of text. 将另一个字符串(在本例中为:字符)附加到已存在的文本值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM