简体   繁体   English

如何将数组中的数组转换为字符串?

[英]How do I convert an array inside an array to a string?

I'm new to programming. 我是编程新手。 I am coding with javascript. 我正在用javascript编码。 I want to convert an array with 3 arrays inside it to one single string and have spaces between each of the different arrays. 我想将其中具有3个数组的数组转换为单个字符串,并在每个不同的数组之间留有空格。

I want to turn this: 我想转这个:

var myArray = [['example'], ['text'], ['hm']]

Into this: 变成这个:

var myString = 'example text hm'

I think you want that to be an array with [] . 我认为您希望将其作为[]的数组。 If that's the case, this is a good use for reduce() combined with join() which will progressively build a concatenated array which you can then join: 如果是这种情况,这对于reduce()join()结合使用是一个很好的用法,它将逐步构建一个级联的数组,然后可以将其加入:

 let myArray = [['example'], ['text', 'text2'], ['hm']] let str = myArray.reduce((all, arr) => all.concat(arr)).join(' ') console.log(str) 

Use nested for-each loops. 使用嵌套的for-each循环。

myString = "";
for each (row in myArray){
    for each (column in row){
        myString = myString + column;
    }
}

In this specific case, you can use the standard Array.join() . 在这种特定情况下,可以使用标准的Array.join() This will invoke the sub-array's .toString() method. 这将调用子数组的.toString()方法。 Usually it returns a string of the items, separated by commas, but Since you've got only a single item in each sub-array, you'll get that item in a string. 通常,它返回一串由逗号分隔的项目,但是由于每个子数组中只有一个项目,因此您将以字符串的形式获得该项目。

 const myArray = [['example'], ['text'], ['hm']] const result = myArray.join(' ') console.log(result) 

You can join them together using Array.join(' ') 您可以使用Array.join('')将它们连接在一起

const sentence = myArray.join(' ')

will return "example text hm" 将返回"example text hm"

The speech marks separated will keep the words separate and stop them joining together. 语音标记分开将使单词分开并阻止它们结合在一起。 If they are together it will join all the strings "exampletexthm" 如果它们在一起,它将连接所有字符串"exampletexthm"

I would also suggest that you use const or let instead of var . 我还建议您使用constlet代替var It can cause some issues. 它可能会引起一些问题。 Article to look at 文章看

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

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