Javascript Random problem?

2019-08-24 17:33发布

var swf=["1.swf","2.swf","3.swf"];
var i = Math.floor(Math.random()*swf.length);

alert(swf[i]); // swf[1]  >> 2.swf

This case ,Random output One number.

How to Random output two different numbers ?

4条回答
仙女界的扛把子
2楼-- · 2019-08-24 18:06

You can use splice to remove the chosen element, then simply select another randomly. The following leaves the original array intact, but if that's not necessary you can use the original and omit the copy. Shown using a loop to demonstrate how to select an arbitrary number of times upto the size of the original array.

var swf=["1.swf","2.swf","3.swf"];
var elementsToChoose = 2;
var copy = swf.slice(0);
var chosen = [];

for (var j = 0; j < elementsToChoose && copy.length; ++j) {
   var i = Math.floor(Math.random()*copy.length);
   chosen.push( copy.splice(i,1) );
}

for (var j = 0, len = chosen.length; j < len; ++j) {
   alert(chosen[j]);
}
查看更多
We Are One
3楼-- · 2019-08-24 18:09

I would prefer this way as the bounds are known (you are not getting a random number and comparing it what you already have. It could loop 1 or 1000 times).

var swf = ['1.swf', '2.swf', '3.swf'],
    length = swf.length,
    i = Math.floor(Math.random() * length);
    firstRandom = swf[i];

// I originally used `delete` operator here. It doesn't remove the member, just
// set its value to `undefined`. Using `splice` is the correct way to do it. 
swf.splice(i, 1);
length--;

var j = Math.floor(Math.random() * length),
    secondRandom = swf[j];


alert(firstRandom + ' - ' + secondRandom);

Patrick DW informed me of delete operator just leaving the value as undefined. I did some Googling and came up with this alternate solution.

Be sure to check Tvanfosson's answer or Deceze's answer for cleaner/alternate solutions.

查看更多
放我归山
4楼-- · 2019-08-24 18:10
var swf = ['1.swf', '2.swf', '3.swf'],

// shuffle
swf = swf.sort(function () { return Math.floor(Math.random() * 3) - 1; });

// use swf[0]
// use swf[1]

Even though the above should work fine, for academical correctness and highest performance and compatibility, you may want to shuffle like this instead:

var n = swf.length;
for(var i = n - 1; i > 0; i--) {
    var j = Math.floor(Math.random() * (i + 1));
    var tmp = swf[i];
    swf[i] = swf[j];
    swf[j] = tmp;
}

Credits to tvanfosson and Fisher/Yates. :)

查看更多
贪生不怕死
5楼-- · 2019-08-24 18:20

This is what I would do to require two numbers to be different (could be better answer out there)

var swf=["1.swf","2.swf","3.swf"];
var i = Math.floor(Math.random()*swf.length);
var j;
do {
    j = Math.floor(Math.random()*swf.length);
} while (j === i); 

alert(swf[i]);
alert(swf[j]);

Edit: should be j===i

查看更多
登录 后发表回答