简体   繁体   English

如何在 javascript 中将整个数组转换为字符串

[英]how to convert whole array to string in javascript

I got a question in the interview that he asked to convert the whole array into a String.我在面试中遇到一个问题,他要求将整个数组转换为String。 I tried with toString() but that's not worked for his output.我尝试使用 toString() 但这对他的 output 不起作用。

input输入

let a=['20','30','50']

expected output预计 output

"['20','30','50']"

Assuming the "output" is the content of this string you want, you can map the values first to wrap them in single-quotes, then join the array with commas and wrap the entire thing in "[...]" .假设“输出”是您想要的这个字符串的内容,您可以先将值map用单引号括起来,然后用逗号连接数组并将整个内容包裹在"[...]"中。

 const a = ['20','30','50']; const str = `"[${a.map(v=>`'${v}'`).join(",")}]"`; console.log(str);

Try this:尝试这个:

let arr = ['1','2','3'];

//this will convert it to string
let arrToString = JSON.stringify(arr);

//you can confirm its type using below code
console.log(typeof(arrToString))

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

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