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
?
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
?
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.
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).
Patrick DW informed me of
delete
operator just leaving the value asundefined
. 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.
Even though the above should work fine, for academical correctness and highest performance and compatibility, you may want to shuffle like this instead:
Credits to tvanfosson and Fisher/Yates. :)
This is what I would do to require two numbers to be different (could be better answer out there)
Edit: should be
j===i