Printing an array with all elements on the same line

Asked

Viewed 816 times

-1

Why when we ride a array, as in the following code:

let x = 0
let array7 = new Array
for(x = 0; x < 50; x++){

    array7[x] = Math.floor(Math.random() * 50 - 10 + 10)

}

let array8 = array7.filter(array7 => array7 < 20)
console.log(array7)
console.log(array8)

the exit of array mounted is all full of line breaks? Do you have how to fix this and show the result in a row? Current output:

Saída atual

In short, why the output is so, and how do I for the elements of array all printed on the same line?

  • where you made that exit like this?

  • 1

    This is who did it. There is no code that solves.

1 answer

6


You are using an inadequate resource. One of the things that few people understand is that there is the data and there is the textual representation of the data. JS, like other languages, have a function toString() that delivers the textual representation of the object. When you have a die printed it takes this textual representation. I have already said in details about this.

It turns out that the textual representation is not always suitable to show to the application user. This works well with scalar values, which are the simple data often considered primitive. When the data is composed it becomes more complicated to define how the textual representation of it should be and in each situation may need to represent it in a different way, so for composite data the standard textual representation provided only serves for debugging purposes. It is not the end of the world to use it to present to the user if it is exactly what you want, but in case it is not, then the solution is to assemble the presentation the way you want.

The question does not speak explicitly but it seemed clear to me that I wanted the values to be presented one by one in a row, probably separated by comma and so I give the solution below.

It has several forms, one of them is using the join().

let array7 = new Array;
for (let x = 0; x < 50; x++) array7[x] = Math.floor(Math.random() * 50 - 10 + 10);
let array8 = array7.filter(array7 => array7 < 20)
console.log(array7.join(", "));
console.log(array8.join(", "));

I put in the Github for future reference.

  • 1

    If the person who denied me tell me what’s wrong I fix it.

  • thank you very much, I knew the Join function but I didn’t think to use in this case, you would recommend me another way to generate several random numbers for an array without using repetition cycles?

  • @gmtlme depends on the need.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.