简体   繁体   中英

Going on a new line when the array reaches a number higher than x

The issue is as followed: i'm trying to make a piece of code that will print all the elements of an array until it reaches an number higher than 30 lets say. When it does reach that number, the code should start on a new line. For example, i have the array:

[5, 34, 8, 31, 7, 5, 4, 39, 9, 10, 11, 32, 14];

When the code is finished, it should print something like this:

5, 34
8, 31
7, 5, 4, 39
9, 10, 11, 32
14      

All i've been able to do so far is:

var array1 = [5, 34, 8, 31, 7, 5, 4, 39, 9, 10, 11, 32, 14];
for (i = 0; i < array1.length; i++){

}

I have no idea how would i continue from here. I've tried different stuff that came through my mind, but nothing worked. Could someone explain? I'm not here just for the solving, but more for the explanation.

Thank you.

Assuming you are writing to the console:

var array1 = [5, 34, 8, 31, 7, 5, 4, 39, 9, 10, 11, 32, 14];

var value = '';
for (var i = 0; i < array1.length; i++) {
    var number = array1[i];
    value += value.length > 0 ? ',' + number : number;
    if (number > 30) {
        console.log(value);
        value = '';
     }
}
console.log(value);

this will print to the console this result:

 5,34
 8,31
 7,5,4,39
 9,10,11,32
 14

value is appended to within every iteration of the loop. If the current number is over 30 then value is written to the console. After value is written to the console it is cleared.

I assume this is what you want :

    function printArray(arr){
          for(var i =0;i<arr.length;i++){
            if( arr[i] > 30){
              console.log('\n');
            }
            console.log(arr[i]);
        }

        printArray([5, 34, 8, 31, 7, 5, 4, 39, 9, 10, 11, 32, 14]);

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.

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