ale*_*lex 21
你的意思是,获得一个随机数组成员?
var strings = ['a', 'b', 'c'];
var randomIndex = Math.floor(Math.random() * strings.length);
var randomString = strings[randomIndex];
Run Code Online (Sandbox Code Playgroud)
如果你的意思是随机字符串,那就有点不同了.
var randomStrLength = 16,
pool = 'abcdefghijklmnopqrstuvwxyz0123456789',
randomStr = '';
for (var i = 0; i < randomStrLength; i++) {
var randomChar = pool.charAt(Math.floor(Math.random() * pool.length));
randomStr += randomChar;
}
Run Code Online (Sandbox Code Playgroud)
当然,您可以跳过pool
变量并String.fromCharCode()
使用97('a'.charCodeAt(0)
)和122('z'.charCodeAt(0)
)之间的随机数作为小写字母等.但是根据您想要的范围(小写和大写,加上特殊字符),使用池更少复杂.
亚历克斯和马赫什是正确的,只是想展示如果我觉得生活危险,我将如何实施他们的解决方案.我做的.
Array.prototype.chooseRandom = function() {
return this[Math.floor(Math.random() * this.length)];
};
var a = [1, 2, 3, 4, 5];
a.chooseRandom(); // => 2
a.chooseRandom(); // => 1
a.chooseRandom(); // => 5
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
7048 次 |
最近记录: |