How do I output array elements in a textarea, placing each element on its own line?
var your_array = [ "Alice", "Bob", "Eve" ];
<textarea id="your_textarea"></textarea>
We can use ArrayList as the intermediate structure and add the elements into the ArrayList using the add () method. ArrayList is a data structure that allows us to dynamically add elements.
First get the element to be inserted, say x. Then get the position at which this element is to be inserted, say pos. Then shift the array elements from this position to one position forward(towards right), and do this for all the other elements next to pos.
To convert a JavaScript array into a string, you can use the built-in Array method called toString . Keep in mind that the toString method can't be used on an array of objects because it will return [object Object] instead of the actual values.
An array has a method to glue all elements together, Array.join
. Without an argument, it would use a comma (,
) as glue. To put every element on a new line, use the newline character (\n
).
var your_array = [ "Alice", "Bob", "Eve" ];
var textarea = document.getElementById("your_textarea");
textarea.value = your_array.join("\n");
<textarea id="your_textarea"></textarea>
Example on JSFiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With