My javascript code is printing only one row. I need it to print 10 rows of 20 characters. -
this coin flipping randomizer. need print out 10 rows , 20 columns. stuck. code seems randomize correctly every time click button, displays 20 columns cannot seem print second row. may simple not catching. appreciated.
javascript code
function toss() { var heads = "x "; var tails = "o "; var rows = 0; while(rows < 10) { var arr = new array(20); for(var = 0; < arr.length; i++) { var val = math.floor( math.random() * 2 ); if(val === 1) { arr[i] = " x"; } else { arr[i] = " y"; } document.getelementbyid("results").innerhtml = arr + "<br />"; } delete arr; rows++ } }
html:
<html> <head> <title>coin flip</title> <script src="toss.js" type="text/javascript"></script> <style> #results { display: block; } </style> </head> <body> push button flip -> <input type="button" onclick="toss()" value=" flip "> <span id="results"></span> </body> </html>
the problem replacing entire results output each time create row new row. need append instead of replace. change this:
document.getelementbyid("results").innerhtml = arr + "<br />";
to:
document.getelementbyid("results").innerhtml += arr + "<br />";
you need move append of result out of inner loop! if leave append within for
loop, see behavior: http://jsfiddle.net/t1s93lqz/3/
jsfiddle: http://jsfiddle.net/t1s93lqz/2/
Comments
Post a Comment