How to concatenate results of a For in Javascript

0

I have the following code that brings me 3 answers in the following way in the Javascript console:

"Prueba 1"
"Prueba 2"
"Prueba 3"

But I need you to show it to me together and not in 3 lines separately. To show it to me in one line:

"Prueba 1", "Prueba 2", "Prueba 3"

This is the For with which I bring the results by the 3 lines separately:

for(let i=0;i<respuesta.output.generic[0].options.length;i++){
var options = respuesta.output.generic[0].options[i].label;
console.log(options);

How could I get these results together?

Thank you very much!

    
asked by Isaac Alejandro 07.12.2018 в 16:59
source

2 answers

2

if you want to show them followed in the console (which is where you say):

    var options = '';
    var ejemplo = {
             options : [1,3,4,'hola',5,'adios']
       };
    for(let i=0;i<ejemplo.options.length;i++){
         options += ejemplo.options[i] +', ';
    }
    console.log(options);

Note: in the example I have changed the attributes of your variable, since I do not know them, but adapt it and it will help you

    
answered by 07.12.2018 / 17:02
source
3

If the information you want to iterate is in an array you can choose to print it with the toString() method or use the join(';') method to indicate the delimiter character, for example:

const array = ['Prueba 1', 'Prueba 2', 'Prueba 3']
console.log(array.toString())

let a = array.join(',')
console.log(a)

Or you can store everything in one variable and print it at the end as follows:

const array = ['Prueba 1', 'Prueba 2', 'Prueba 3']
let result = '';
for(i = 0; i<array.length;i++){
  result += array[i].concat(',');
}
result.substring(0,result.length-1)
console.log(result)

References

  • join ()
  • toString ()
  • answered by 07.12.2018 в 17:16