如何在Javascript中使用以下条件生成随机数
注意:由于旧版原因,我不想使用任何JS库
我尝试了下面的代码,但例如与标准不匹配,有时它根本不包含数字...。
function randomString(length, chars) {
var mask = '';
if (chars.indexOf('a') > -1) mask += 'abcdefghijklmnopqrstuvwxyz';
if (chars.indexOf('A') > -1) mask += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
if (chars.indexOf('#') > -1) mask += '0123456789';
var result = '';
for (var i = length; i > 0; --i) result += mask[Math.round(Math.random() * (mask.length - 1))];
return result;
}
document.write(randomString(12, 'aA#'));
有更好的方法吗?
操作方法如下:生成一个代表您的条件的数组,将其随机排列并填充该数组。
例子:
function makeRandomString(criteria) {
// From http://stackoverflow.com/q/2450954/3371119
function shuffle(array) {
var currentIndex = array.length,
temporaryValue, randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
// Choose a random character from a string
function chooseRandom(str) {
return str[Math.floor(Math.random() * str.length)];
}
// Shuffle the criteria
shuffle(criteria);
var result = "";
// Build the resulting string by choosing a random character from each part
for (var i = 0; i < criteria.length; ++i) result += chooseRandom(criteria[i]);
return result;
}
用法示例:
// Some constants explaining the criteria
var lowercase = "abcdefghijklmnopqrstuvwxyz";
var uppercase = lowercase.toUpperCase();
var numbers = "0123456789";
// Note: if you don't like typing all that, change the names to L, N, and U
var criteria = [lowercase, lowercase, lowercase, lowercase, // 4 lowercase
numbers, numbers, numbers, numbers, // 4 numbers
uppercase, uppercase, uppercase, uppercase // 4 uppercase
];
console.log(makeRandomString(criteria));
甚至更好(更少键入):
function repeat(elem, n) {
var result = [];
for (var i = 0; i < n; ++i) result.push(elem);
return result;
}
var criteria = repeat(lowercase, 4)
.concat(repeat(uppercase, 4))
.concat(repeat(numbers, 4));
console.log(makeRandomString(criteria));
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句