var fruits = ["Banana", "Orange", "Apple", "Mango"];
If I had the above array and wanted to output it to the user in the DOM as ["Banana", "Orange", "Apple", "Mango"]
What would be the best way to do this?
I have tried fruits.toString();
which outputs as Banana,Orange,Apple,Mango
Use JSON.stringify
JSON.stringify(fruits)
If for some reason you don't want to use JSON, you could also use join.:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var fruitsString = '["' + fruits.join('", "') + '"]';
Note: For mulitdimensional arrays see javascript - Convert array to string while preserving brackets.
in order to do that you'll need to iterate through the array and build the string from scratch.
so something like this:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
// first make sure that each fruit is between quotes
var fruitsResult = fruits.map(function(fruit) {
return '"' + fruit + '"';
});
// join the fruits with the comma's in between
var result = fruitsResult.join(', ');
// add the final brackets around it
result = '[' + result + ']'
This is a basic solution that you can either add as a single function somewhere and pass the array to our you can extend the Array prototype with your own method so you can call fruits.toMyStringFunction(). It's up to you how you want to implement this.
Note: that I'm using the Array.prototype.map() method that is supported in modern browsers but will cause some issues with IE8 and lower. This step can also be done using a for loop but this is more elegant.
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