Javascript Random problem? -


var swf=["1.swf","2.swf","3.swf"]; var = math.floor(math.random()*swf.length);  alert(swf[i]); // swf[1]  >> 2.swf 

this case ,random output one number.

how random output two different numbers ?

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 above should work fine, academical correctness , highest performance , compatibility, may want shuffle instead:

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

credits tvanfosson , fisher/yates. :)


Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -