I have an array of 100 random numbers between 1 and 49.
I would like to print out the array in rows of twelve elements, instead of printing the array in a single line.
Here is the code I have
<script type ="text/javascript">
var arr = [];
for (var i = 0, l = 100; i < l; i++) {
arr.push(Math.round(Math.random() * 49)+1)
}
document.write(arr);
document.write("\n");
</script>
I need to print the array in rows with 12 elements per row and also need to find the smallest element in the array.
You could try using splice
:
while (arr.length > 0) {
document.write(arr.splice(0, 12))
}
However, after running that code the array will be []
. If you don't want to modify the array, use slice
instead:
for (var i = 0; i < arr.length; i += 12) {
document.write(arr.slice(i, i + 12))
}
This would be the conventional way of doing it. The array is reset however. Let us know more detail on your requirements.
var arr = [];
function getRandom( num ){
return Math.round(Math.random() * num)+1;
}
var counter = 0;
for (var i = 0; i < 100; i++) {
arr.push(getRandom( 49 ));
counter++;
if( counter >= 12 ){
document.write(arr);
document.write("<br/>");
arr = [];
counter = 0;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.