简体   繁体   中英

Javascript, Array to string format

I am in a situation in my Ionic project to convert array to string format(array). Here is the example

var fruits = ["Banana", "Orange", "Apple", "Mango"];

should be converted to

var strFruits = "['Banana', 'Orange', 'Apple', 'Mango']";

I can do it using loop and string operation, but there should be an easy way to resolve this.

Try:

 const fruits = ['Banana', 'Apple', 'Orange']; const format = "['" + fruits.join("', '") + "']"; console.log(format); // => ['Banana', 'Apple', 'Orange'] 

Or as suggested in the comments, using JSON.stringify :

 const fruits = ['Banana', 'Apple', 'Orange']; const format = JSON.stringify(fruits); console.log(format); // => ["Banana", "Apple", "Orange"] 

I personally do not prefer the last one, because you are forced to use double quotes, and the only way to change that is using RegEx.

您可以使用JSON.stringify(fruits)或只是concat "["+fruits.toString()+"]"

For

const fruits = ["Banana", "Orange", "Apple", "Mango"];

You could do:

console.log(JSON.stringify(fruits));
// ["Banana","Orange","Apple","Mango"]

This returns a string that can be parsed back to JS using JSON.parse() which seems to be exactly what you need

To the scope of your question, this would be valid too:

console.log(`['${fruits.join("', '")}']`);
// ['Banana', 'Orange', 'Apple', 'Mango']

This would return what you asked for with the single quotes, but using JSON.stringify() has the added advantage that the resulting string can always be parsed back (I'ts always valid JSON)

JSON.parse(`['${fruits.join("', '")}']`);
// Uncaught SyntaxError: Unexpected token ' in JSON at position 1

 console.log(JSON.stringify(["Banana", "Orange", "Apple", "Mango"]).replace(/"/g, "'")) 

但是我认为方法“ join()”的第一个变体更适合这种情况,因为如果文本包含双引号,则replace()会以错误的方式工作。

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