简体   繁体   English

Javascript,数组转换为字符串格式

[英]Javascript, Array to string format

I am in a situation in my Ionic project to convert array to string format(array). 我在Ionic项目中处于一种将数组转换为字符串格式(数组)的情况。 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 : 或者按照注释中的建议,使用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. 我个人不喜欢最后一个,因为您被迫使用双引号,而唯一的更改方法是使用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 这将返回一个可以使用JSON.parse()解析为JS的字符串,这似乎正是您所需要的

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.stringify()有一个额外的优势,就是始终可以解析返回的字符串(我并不总是有效的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()会以错误的方式工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM