简体   繁体   English

在行中打印数组javascript

[英]printing array in rows javascript

I have an array of 100 random numbers between 1 and 49. 我有一个1到49之间的100个随机数的数组。

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. 我需要按行打印数组,每行包含12个元素,还需要找到数组中最小的元素。

You could try using splice : 您可以尝试使用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: 如果您不想修改数组,请改用slice

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;
     }

 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM