方法一(其实是毫秒时间数字字符串):
Javascript代码
- function randomString() {
- return ‘‘ + new Date().getTime();
- }
方法二(随机字母数字字符串):
Javascript代码
- 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);
使用Javascript实现随机字符串
时间: 2024-11-05 22:32:35