开发者

In Javascript, how do I generate a random element out of a list?

开发者 https://www.devze.com 2023-01-30 15:43 出处:网络
Suppose I have a list of strings. How do I g开发者_运维技巧enerate a random one?You mean, get a random array member?

Suppose I have a list of strings. How do I g开发者_运维技巧enerate a random one?


You mean, get a random array member?

var strings = ['a', 'b', 'c'];

var randomIndex = Math.floor(Math.random() * strings.length);

var randomString = strings[randomIndex];

See it on jsFiddle.

If you mean a random string, it is a little different.

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;   
}

See it on jsFiddle.

Of course, you can skip the pool variable and do String.fromCharCode() with a random number between 97 ('a'.charCodeAt(0)) and 122 ('z'.charCodeAt(0)) for lowercase letters, etc. But depending on the range you want (lowercase and uppercase, plus special characters), using a pool is less complex.


Alex and Mahesh are right on, just wanted to demonstrate how I might implement their solutions if I felt like living dangerously. Which I do.

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


var randomString = myStrings[Math.floor(Math.random() * myStrings.length)]


var rand = 0; 
var newPic = []; 
var pic = [1,2,3] //length = 18 for ( var i=0; i<18; i++ ){ 
    rand = Math.floor(Math.random()*19); 
    newPic.push(pic[rand-1].slice()); 
} alert(newPic); 
0

精彩评论

暂无评论...
验证码 换一张
取 消