使用Javascript实现随机字符串
方法一(其实是毫秒时间数字字符串):
- function randomString() {
- return '' + new Date().getTime();
- }
方法二(随机字母数字字符串):
- var alpha_num_chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz'.split('');
- function randomString(length) {
- if (! length) {
- length = Math.floor(Math.random() * alpha_num_chars.length);
- }
- var str = '';
- for (var i = 0; i < length; i++) {
- str += alpha_num_chars[Math.floor(Math.random() * alpha_num_chars.length)];
- }
- return str;
- }
- // generate a random string of random length
- randomString();
- // generate a random string of length 8
- randomString(8);