限制随机字符串生成器的输出长度

时间:2014-06-15 15:55:14

标签: javascript random output

我的随机生成器主要使名称偏大。根据我的阅读,如果您使用.round.ceil.floor,这可能是一个因素。它也应该使名称不小于3且不大于13。

将名称添加到名称后,一些名称分别为2和14等,所以我再次修改它。我对此有错误吗?

var nameLength = Math.floor(Math.random() * (13 - 3) + 3); /* min 3 max 13*/
var compareLetter = 0;
var randomLetter = "";
var randomName = "";
var capitolLetter = "";
var checkLetter = 0;
var nameTitle = "XXX"; /* titles add _ between title and name*/
var nameLetters = [
    ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"],
    ["a", "e", "i", "o", "u"],
    ["b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z"]
];
if (nameTitle !== "") { /* my attempt to subtract title length +1 from name length if over 13*/
    nameLength = nameLength + (nameTitle.length + 1);
    if (nameLength > 13) {
        nameLength = nameLength - (nameLength - 13);
    }
}
for (i = 0; i < nameLength; i++) {
    randomLetter = nameLetters[compareLetter][Math.floor(Math.random() * nameLetters[compareLetter].length)];
    checkLetter = nameLetters[1].indexOf(randomLetter);
    if (checkLetter > -1) { /* my version of keeping consanants and vowels from stacking up */
        compareLetter = 2;
    } else {
        compareLetter = 1;
    }
    if (randomName.length < 1) { /* my version to keep first letter capitolized*/
        capitolLetter = randomLetter.toUpperCase();
        randomName = randomName + capitolLetter;
    } else {
        randomName = randomName + randomLetter;
    }
}
if (nameTitle !== "") {
    alert(nameTitle + "_" + randomName);
} else {
    alert(randomName);
}
alert(nameLength);
alert(randomName.length);

任何指导都将不胜感激。

0 个答案:

没有答案