我正在使用以下JavaScript。最终结果是显示序列字符。 但我想按顺序显示字母数字。我该怎么做?
var disp = '';
var string = '';
var i;
var chars = "0123456789abcdefghiklmnopqrstuvwxyz";
var ran_unrounded;
var ran_number;
var rnum;
for (i = 0; i < 5; i++) {
rnum = Math.floor(Math.random() * chars.length);
string += chars.substring(rnum, rnum + 1);
ran_unrounded = Math.random() * 3;
ran_number = Math.floor(ran_unrounded);
//document.write(chars.substring(rnum, rnum + 1));
// alert('rnum', rnum, '--', rnum + 1);
disp = chars.substring(rnum, rnum + 8);
}
答案 0 :(得分:1)
好的,所以从上面评论中的澄清,要求是生成一个包含两个随机“单词”的字符串,其中每个“单词”从预定义的一组可用字符中随机选择四个字符。
以下是一种方法:
var chars = "0123456789abcdefghiklmnopqrstuvwxyz";
function getWord(numChars) {
var word = "",
i;
for (i = 0; i < numChars; i++)
word += chars.charAt(Math.floor(Math.random() * chars.length));
return word;
}
function getWords(numWords, numCharsPerWord) {
var words = [],
i;
for (i = 0; i < numWords; i++)
words.push(getWord(numCharsPerWord));
return words.join(" ");
}
console.log( getWords(2, 4) ); // "a8ak 1wp9"
console.log( getWords(3, 4) ); // "7ua1 zh80 yy3r"
console.log( getWords(2, 5) ); // "j5ms2 e4xn8"