Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
533 views
in Technique[技术] by (71.8m points)

javascript - 在JavaScript中生成随机字符串/字符(Generate random string/characters in JavaScript)

I want a 5 character string composed of characters picked randomly from the set [a-zA-Z0-9] .

(我想要一个由从[a-zA-Z0-9]随机挑选的字符组成的5个字符串。)

What's the best way to do this with JavaScript?

(用JavaScript做到这一点的最佳方法是什么?)

  ask by Tom Lehman translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

 let r = Math.random().toString(36).substring(7); console.log("random", r); 

Note: The above algorithm has the following weaknesses:

(注意:以上算法具有以下缺点:)

  • It will generate anywhere between 0 and 6 characters due to the fact that trailing zeros get removed when stringifying floating points.

    (由于在对浮点进行字符串化时会删除尾随零,因此它将生成0到6个字符之间的任意位置。)

  • It depends deeply on the algorithm used to stringify floating point numbers, which is horrifically complex.

    (这在很大程度上取决于用于对浮点数进行字符串化的算法,该算法极其复杂。)

    (See the paper "How to Print Floating-Point Numbers Accurately" .)

    ((请参阅论文“如何准确打印浮点数” 。))

  • Math.random() may produce predictable ("random-looking" but not really random) output depending on the implementation.

    (Math.random()可能会产生可预测的(“看起来很随机”,但不是真正随机的)输出。)

    The resulting string is not suitable when you need to guarantee uniqueness or unpredictability.

    (当您需要保证唯一性或不可预测性时,结果字符串不适合。)

  • Even if it produced 6 uniformly random, unpredictable characters, you can expect to see a duplicate after generating only about 50,000 strings, due to the birthday paradox .

    (即使它产生了6个均匀随机且不可预测的字符,由于生日悖论 ,您也可以期望仅生成大约50,000个字符串后看到重复项。)

    (sqrt(36^6) = 46656)

    ((sqrt(36 ^ 6)= 46656))


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...